VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-adjacency-list-for-a-directed-graph/

⇱ Adjacency List from Edges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Adjacency List from Edges

Last Updated : 5 Apr, 2026

Given an undirected graph with V vertices (0-based indexing) and edges, create an adjacency list of the graph.

Examples:

Input: V = 5, edges = [[0,1], [0,4], [4,1], [4,3], [1,3], [1,2], [3,2]]

šŸ‘ blobid2_1744376584

Output: [[1,4], [0,2,3,4], [1,3], [1,2,4], [0,1,3]]

Explanation:

  • Node 0 is connected to 1 and 4.
  • Node 1 is connected to 0,2,3 and 4.
  • Node 2 is connected to 1 and 3.
  • Node 3 is connected to 1,2 and 4.
  • Node 4 is connected to 0,1 and 3.

Input: V = 4, edges = [[0,3], [0,2], [2,1]]

šŸ‘ blobid5_1744376643

Output: [[2,3], [2], [0,1], [0]]

Explanation:

  • Node 0 is connected to 2 and 3.
  • Node 1 is only connected to 2.
  • Node 2 is connected to 0 and 1.
  • Node 3 is only connected to 0.

Consider the graph V = 4, edges = [[0,3], [0,2], [2,1]]. Here are the steps to build its adjacency list.

šŸ‘ blobid5_1744376643

Step 1: Initialize empty lists for each vertex: 0: [], 1: [], 2: [], 3: [], 4: []

Step 2: For each edge [u, v], since this is undirected, we add v to u's list and u to v's list.

  • Edge [0,3] - Add 3 to 0’s list and 0 to 3’s list: 0: [3], 1: [], 2: [], 3: [0]
  • Edge [0,2] - Add 2 to 0’s list and 0 to 2’s list: 0: [3, 2], 1: [], 2: [0], 3: [0]
  • Edge [2,1] - Add 1 to 2’s list and 2 to 1’s list: 0: [3, 2], 1: [2], 2: [0, 1], 3: [0]

Step 3: Final adjacency list: 0: [3, 2], 1: [2], 2: [0, 1], 3: [0]. Each list represents the neighbors of that vertex.


Output
0: 3 2 
1: 2 
2: 0 1 
3: 0 

Time Complexity:  O(V+E), where V = number of vertices, E = number of edges.
Auxiliary Space: O(V + E) (average case), O(V²) (worst case if fully connected)

Comment