Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Concept

Adjacency List

How to store a graph
step 1 / 18
adjacency list
0
1
2
3
adjacency list
  • 0:[]
  • 1:[]
  • 2:[]
  • 3:[]
Build & read an adjacency list
1adj = map node -> [neighbours]
2for each node u:
3 adj[u] = []
4 for each edge (u, v): adj[u].append(v)
5// traverse:
6for v in adj[u]: visit(v) // read neighbours directly
7// matrix alternative costs O(V^2) space
state
  • nodes4
  • edges5
  • listO(V+E)
  • matrixO(V²)

line 1How do we store a graph in code? The adjacency list keeps, for each node, a list of its direct neighbours. It uses O(V + E) memory — only the edges that exist — which is ideal for sparse graphs. The alternative, an adjacency matrix, is a V×V grid costing O(V²) whether or not the edges exist.