Browse Curriculum
Depth-First Search
Medium

Graph Representation: Adjacency List

How to build and store graphs efficiently.

Representing 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 / 1

Visualization coming soon...

Initializing...

1x

Visualizing Graph Edges.

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.