Depth-First Search
Medium
Graph Representation: Adjacency List
How to build and store graphs efficiently.
15 min
Solve on LeetCodeRepresenting a Graph
We don't get 'Node' objects automatically. Often, inputs are given as a list of Edges or integer pairs.
Input: n = 4, edges = [[0,1], [0,2], [2,3]].
We need to convert this into a structure that allows fast lookups of neighbors: getNeighbors(u).
Adjacency Matrix vs List
Adjacency Matrix: A 2D array adj[n][n] where adj[i][j] = 1 if connected.
- Pros: O(1) edge check.
- Cons: O(N²) space. Slow to iterate neighbors O(N).
Adjacency List: A Map or Array of Lists where adj[i] contains a list of neighbors.
- Pros: O(V + E) space. Fast to iterate neighbors.
- Verdict: Almost always use Adjacency List for interview problems unless N is very small or the graph is dense.
Visualization
Step 1 / 11
Adjacency List(Map<Node, List>)
0:
[]
1:
[]
2:
[]
3:
[]
Initialize empty Adjacency List for N=4 nodes.
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Representing a Graph
- Adjacency Matrix vs List
- Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Building the Graph (Template)
- Complexity Analysis
- Summary
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
