3.5.2Graphs

Representations — adjacency matrix (space O(V²)), adjacency list (space O(V+E))

2,035 words9 min readdifficulty · medium

WHAT are we representing?

The key fact controlling all space costs: 0E(V2)=V(V1)2=O(V2)(undirected, no self-loops)0 \le E \le \binom{V}{2} = \frac{V(V-1)}{2} = O(V^2)\quad(\text{undirected, no self-loops})

So at most there are V2/2\sim V^2/2 edges. A graph where EV2E \approx V^2 is called dense; one where EVE \approx V (or EV2E \ll V^2) is called sparse. This single distinction decides which representation wins.


Representation 1 — Adjacency Matrix

WHY it costs O(V2)O(V^2): we allocate one cell for every ordered pair (u,v)(u,v) — that's V×V=V2V \times V = V^2 cells — regardless of how many edges actually exist. Even an empty graph with V=1000V=1000 eats a million cells.


Representation 2 — Adjacency List

WHY it costs O(V+E)O(V+E): we store the VV list headers (+V+V) plus, across all lists, exactly one entry per edge-endpoint. Each undirected edge appears in two lists, so total entries =2E=O(E)= 2E = O(E). Directed: EE entries. Sum: O(V+E)O(V+E). Nothing is stored for absent edges — that's the saving.


Figure — Representations — adjacency matrix (space O(V²)), adjacency list (space O(V+E))

HOW they compare (the 80/20 table)

Operation Adjacency Matrix Adjacency List
Space O(V2)O(V^2) O(V+E)O(V+E)
Edge query isEdge(u,v)? O(1)O(1) O(degu)O(\deg u)
List neighbors of uu O(V)O(V) (scan whole row) O(degu)O(\deg u)
Add edge O(1)O(1) O(1)O(1)
Iterate all edges O(V2)O(V^2) O(V+E)O(V+E)
Best for dense graphs / fast edge checks sparse graphs (the common case)

Worked Examples


Common Mistakes (Steel-manned)


Active Recall

Recall Quick self-test (hide and answer)
  1. Why exactly O(V2)O(V^2) for the matrix even with few edges?
  2. Why 2E2E and not EE entries for an undirected list?
  3. Which representation makes isEdge(u,v) O(1)O(1)?
  4. For which graph type do their space costs become equal?

Answers: 1) one cell per ordered pair, edges irrelevant. 2) edge stored in both endpoints' lists. 3) matrix. 4) dense, E=Θ(V2)E=\Theta(V^2).

Adjacency matrix space complexity
O(V2)O(V^2) — one cell per ordered pair of vertices
Adjacency list space complexity
O(V+E)O(V+E)VV headers plus 2E2E (undirected) edge entries
Why is matrix O(V2)O(V^2) even when the graph has few edges
It allocates a cell for every pair (u,v)(u,v) regardless of whether the edge exists
How many list entries does one undirected edge create
Two — it is stored in both endpoints' neighbor lists
Time to check isEdge(u,v) in a matrix
O(1)O(1) — direct index A[u][v]
Time to check isEdge(u,v) in a list
O(degu)O(\deg u) — must scan u's neighbor list
Time to list all neighbors of u in a matrix
O(V)O(V) — scan the entire row
Time to list all neighbors of u in a list
O(degu)O(\deg u)
Default representation for sparse graphs
Adjacency list
When does the matrix's space tie with the list's
Dense graphs where E=Θ(V2)E=\Theta(V^2)
Property of an adjacency matrix for an undirected graph
It is symmetric, A=ATA=A^T
Meaning of (Ak)[u][v](A^k)[u][v]
Number of walks of length exactly kk from uu to vv
Max number of edges in an undirected simple graph on V vertices
(V2)=V(V1)2\binom{V}{2}=\frac{V(V-1)}{2}
Recall Feynman: explain to a 12-year-old

Imagine your class and who is friends with whom. Method 1 (grid / matrix): draw a big checkerboard with every kid's name on the top and side. Put an ✗ in a square if those two are friends. Super fast to check any pair — but you waste a square even for the millions of pairs who aren't friends. Big class = giant grid. Method 2 (lists): give each kid a sticky note listing only their friends. Tiny if friendships are few. To check if Amy and Ben are friends you read Amy's note — a little slower, but no wasted space. Few friendships → use sticky notes (list). Everyone-knows-everyone → use the grid (matrix).

Connections

  • Breadth-First Search (BFS) — runs in O(V+E)O(V+E) because it uses adjacency lists.
  • Depth-First Search (DFS) — same O(V+E)O(V+E) traversal bound.
  • Floyd-Warshall Algorithm — prefers the adjacency matrix (O(1)O(1) edge weight access).
  • Dijkstra's Algorithm — adjacency list + priority queue for sparse graphs.
  • Big-O Notation — the space/time trade-off vocabulary used here.
  • Sparse vs Dense Graphs — the property that decides the choice.
  • Matrix Multiplication — explains (Ak)(A^k) counting walks.

Concept Map

stored as

stored as

dense E~V squared

sparse E~V

space

answers edge query

undirected

A to power k

space

list all neighbors

trade space vs speed

Graph G=V,E

Adjacency Matrix

Adjacency List

edge count 0..O(V squared)

O(V squared) all pairs

is u-v edge in O(1)

symmetric A = A transpose

counts walks length k

O(V+E) only real edges

scan neighbors fast

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, graph ka matlab hai "kaun kis se connected hai." Ab computer me ye connection store karne ke do main tareeke hain. Pehla hai adjacency matrix — ek V×VV \times V ka grid bana lo, har cell A[u][v] me 1 likho agar edge hai, warna 0. Problem ye hai ki chahe edges 4 ho ya 0, tum har pair ke liye ek box reserve karte ho, isliye space O(V2)O(V^2) ho jaata hai. Plus point: "kya u aur v ke beech edge hai?" ye sawaal O(1)O(1) me answer ho jaata hai — bas index karo.

Doosra tareeka hai adjacency list — har vertex ke liye sirf uske actual neighbors ki ek list rakho. Yahan tum absent edges ke liye kuch store hi nahi karte, isliye space sirf O(V+E)O(V+E)VV headers plus har undirected edge ke do entries (2E2E). Ye real-world graphs ke liye perfect hai kyunki zyadatar graphs sparse hote hain (edges kam, vertices zyada). Bas thoda dhyaan: edge check karne ke liye list me O(degu)O(\deg u) time lagta hai, instant nahi.

Yaad rakhne ka simple rule: agar graph dense hai (sabhi sabse connected, jaise EV2E \approx V^2) ya VV chhota hai ya tumhe baar-baar fast edge check chahiye (jaise Floyd-Warshall me), to matrix lo. Warna by default list hi best hai — BFS/DFS bhi list ke saath O(V+E)O(V+E) me chalte hain, jo bahut fast hai. Bas ye trade-off — space vs edge-query speed — pura topic isi pe ghoomta hai.

Go deeper — visual, from zero

Test yourself — Graphs

Connections