Chapter 20 · Graphs

Graph Representation

The same graph can be stored in memory three ways: adjacency list, adjacency matrix, or edge list. The choice affects every algorithm's time and space complexity. Understanding this tradeoff is essential before implementing any graph algorithm.

Adjacency list or adjacency matrix?

An adjacency list stores each node's neighbours in a list. It uses O(V + E) memory and is the right default for most real graphs, which are sparse. An adjacency matrix is a V × V grid where matrix[a][b] says whether an edge exists. It checks an edge in O(1) but always uses O(V²) memory, so it suits small or dense graphs.

const edges = [["A", "B"], ["A", "C"], ["B", "D"]];

// adjacency list
const list = {};
for (const [a, b] of edges) { (list[a] ??= []).push(b); (list[b] ??= []).push(a); }

// adjacency matrix
const ids = ["A", "B", "C", "D"], idx = Object.fromEntries(ids.map((v, i) => [v, i]));
const matrix = ids.map(() => Array(ids.length).fill(0));
for (const [a, b] of edges) matrix[idx[a]][idx[b]] = matrix[idx[b]][idx[a]] = 1;

Example graph

Vertices: A, B, C, D, E     Edges: (A,B), (A,C), (B,D), (C,D), (D,E)

Undirected, unweighted. 5 vertices (V=5), 5 edges (E=5).

Live demo — build a directed graph

Add and remove directed edges. The adjacency list updates in real time so you can compare it to the matrix representation below.

Directed Graph — adjacency list

V=5, E=5
ABCDE

Adjacency List

A→BC
B→D
C→D
D→E
E→∅
fromto

Adjacency list

Each vertex maps to a list of its neighbors. Store only the edges that exist.

A→
BC
B→
AD
C→
AD
D→
BCE
E→
D
adjacency-list.pseudo
1// Build adjacency list from edge list
2graph <- Map[vertex -> List[vertex]]
3 
4addEdge(u, v): // undirected
5 graph[u].append(v)
6 graph[v].append(u) // both directions
7 
8neighbors(u) -> List[vertex]:
9 return graph[u] // O(1)
10 
11hasEdge(u, v) -> bool: // O(degree(u))
12 return v in graph[u]

Adjacency matrix

A V×V boolean (or weight) matrix. matrix[i][j] = 1 means edge from vertex i to j.

ABCDE
A01100
B10010
C10010
D01101
E00010
adjacency-matrix.pseudo
1// V x V matrix, indices 0..V-1
2matrix <- 2D array[V][V] initialized to 0
3 
4addEdge(u, v): // undirected
5 matrix[u][v] <- 1
6 matrix[v][u] <- 1 // symmetric
7 
8hasEdge(u, v) -> bool: // O(1) — direct lookup!
9 return matrix[u][v] == 1
10 
11neighbors(u) -> List[vertex]: // O(V) — scan full row
12 result <- []
13 for i in 0..V-1:
14 if matrix[u][i] == 1: result.append(i)
15 return result

Comparison

OperationAdj. ListAdj. Matrix
SpaceO(V + E)O(V²)
hasEdge(u, v)O(degree(u))O(1)
neighbors(u)O(degree(u))O(V)
addEdgeO(1)O(1)
removeEdgeO(degree(u))O(1)
Best forSparse graphs (E << V²)Dense graphs (E ≈ V²)

Edge list (simple)

Just store all edges as pairs. Simplest representation. Used in algorithms that process all edges (Kruskal's MST). O(E) space. hasEdge is O(E) — scan all edges.

// edge list

edges = [(A,B), (A,C), (B,D), (C,D), (D,E)]

// weighted version

edges = [(A,B,4), (A,C,2), (B,D,5), (C,D,1), (D,E,3)]

Complexity summary

adjacency list space — ideal for sparse graphsO(V + E)

O(V + E) time

adjacency matrix space — V^2 even if only a few edges existO(V^2)

O(V^2) time

edge list space — just the edges, nothing elseO(E)

O(E) time

🎯 Quick Check

A social network has 1 billion users but each user has on average only 200 friends. Which representation is better?

💡Weighted graphs in adjacency list
For weighted graphs, store pairs (neighbor, weight) instead of just neighbor: graph[u] = [(v1, w1), (v2, w2), ...]. For adjacency matrix, store the weight value instead of 1, and use a sentinel value (0 or infinity) for no edge.

Graph Representation: summary

Key points

  • For weighted graphs, store [neighbour, weight] pairs in the list.
  • Iterating a node's neighbours: O(degree) with a list, O(V) with a matrix.
  • An edge list (an array of pairs) is the simplest format, and it's what Kruskal's algorithm uses.

Frequently asked questions

›Which graph representation should I use?

An adjacency list in almost all cases. Use a matrix only for small, dense graphs or when you need constant-time edge checks.