Skip to content

Graphs: Adjacency List

Devrath edited this page Mar 14, 2024 · 4 revisions

What is Adjacency List

Screenshot 2024-03-10 at 10 26 15 PM
  • Here we have an array of linked lists.
  • In every element of the array, We have a linked list.
  • The linked list contains the index of adjacent neighbors of a given node
  • The john is present in the 0 index and the linked-list at zero position contains the edges 1, 2, and 3 meaning that the john is connected to Mary, bob and Alice.

Space efficiency

  • We are storing only the edges that exist, so this is more space-efficient than the matrix.
  • We have V vertices and if E represents the number of edges. The space complexity of the graph is (V+E).

A Dense Graph

Screenshot 2024-03-11 at 10 27 36 AM
  • When every node is connected to every other node in the tree, It is called a dense graph.
  • Here is the total number of edges (Because every node is connected to all other nodes apart from itself)
E = V * (V-1) = V2-V = V2

Time Complexities

Adding a new node

  • This just involves adding an element to the list.
  • Complexity O(1)

Removing a new node

  • Here there are two steps
    • Delete the node.
    • Also remove all the usages of it, For which other nodes are connected to it. So we will iterate the array and in each array, we visit individual nodes in the list and remove them.
  • Iterating the array --> There are n items --> The complexity is O(V).
  • In each iteration, We need to remove the target node from each linked list. So if the graph has E edges there are E nodes across all the linked lists.
  • Time complexity is O(E+V)
  • In a dense graph --> O(V2)
Clone this wiki locally