Why do massive graph engines like Neo4j, PageRank, and competitive programming speed demons abandon Adjacency Lists of linked vectors in favor of Compressed Sparse Row (CSR) flat arrays?
In 30 Seconds
A Graph $G = (V, E)$ models arbitrary many-to-many relationships between vertices ($V$) and edges ($E$). Choosing the right memory layout determines whether your graph traversal finishes in 5 milliseconds or runs out of RAM: Adjacency Matrices take $O(V^2)$ memory for O(1) edge checks; Adjacency Lists take $O(V + E)$ memory for sparse networks; and Compressed Sparse Row (CSR) packs all edges into two flat contiguous arrays for zero-pointer-chasing CPU cache speed.
Under the Hood: Adjacency Matrix vs. Adjacency List vs. Compressed Sparse Row (CSR)
- Adjacency Matrix ($O(V^2)$ Space — Bitset Acceleration): For $V = 100,000$, a 2D array requires $10^{10}$ cells (~40 GB RAM—instant crash!). However, for dense graphs with $V \le 2,000$, packing rows as Python big-ints or C++
std::bitsetchecks triangles and transitive closures 64 bits per CPU cycle! - Standard Adjacency List ($O(V + E)$ Space): Stores a list of neighbor lists (`adj[u]`). Easy to mutate dynamically, though each inner list lives in a separate heap allocation.
- Compressed Sparse Row (CSR — The Competitive Programmer & HPC Secret): Packs all $E$ edges into a single flat
edgesarray, and uses ahead_offsetarray of length $V + 1$ where vertexu's neighbors sit contiguously atedges[offset[u] : offset[u + 1]]! Zero heap pointers, 100% L1 cache line spatial locality!
Picture This
Directed Graph: 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0
COMPRESSED SPARSE ROW (CSR) IN TWO CONTIGUOUS RAM ARRAYS:
offset[]: [ 0, 2, 3, 4 ] <-- Neighbors of u are at edges[offset[u] : offset[u+1]]
edges[]: [ 1, 2 | 2 | 0 ]
^ ^ ^
u=0 u=1 u=2
Show Me The Code
# Day 25: Graph Representations (Adjacency List + Compressed Sparse Row CSR) in Python
class CSRGraph:
"""Static, cache-friendly Compressed Sparse Row (CSR) graph representation."""
def __init__(self, num_vertices, directed_edges):
self.V = num_vertices
self.offset = [0] * (num_vertices + 1)
# 1. Count out-degree of each vertex
for u, _ in directed_edges:
self.offset[u + 1] += 1
# 2. Prefix sums compute exact starting index for each vertex
for i in range(num_vertices):
self.offset[i + 1] += self.offset[i]
# 3. Populate flat contiguous edges array
self.edges = [0] * len(directed_edges)
cursor = self.offset[:]
for u, v in directed_edges:
self.edges[cursor[u]] = v
cursor[u] += 1
def neighbors(self, u):
"""Returns contiguous slice of neighbors for vertex u."""
return self.edges[self.offset[u] : self.offset[u + 1]]
if __name__ == "__main__":
g = CSRGraph(3, [(0, 1), (0, 2), (1, 2), (2, 0)])
print("Neighbors of 0 (CSR):", g.neighbors(0)) # [1, 2]
Speed & Memory
| Representation | Space | Check Edge (u, v) | Iterate Neighbors of u | Dynamic Edge Add |
|---|---|---|---|---|
| Adjacency Matrix | O(V²) | O(1) | O(V) | O(1) |
| Adjacency List | O(V + E) | O(deg(u)) | O(deg(u)) | O(1) |
| CSR Flat Arrays | O(V + E) (lowest overhead) | O(deg(u)) | O(deg(u)) (L1 cache optimal) | O(V + E) rebuild |
Traps To Avoid
- Trap 1: Using an Adjacency Matrix when $V > 5,000$ in sparse graphs ($E \approx 2V$). Fix: Always check $V^2$ memory first—use Adjacency Lists or CSR when $E \ll V^2$.
- Trap 2: Multiplying row lists via
[[0] * V] * Vin Python. Fix: Always use list comprehension[[0] * V for _ in range(V)]so rows don't alias the same list object.
Practice
- Easy: Convert an edge list into an undirected Adjacency List and find the vertex with maximum degree.
- Medium: Find the "Town Judge" among $N$ people given trust pairs in O(V + E) time and O(V) space using in-degree minus out-degree.
- Hard: Count the number of triangles ($u - v - w - u$) in an undirected graph in O(E * sqrt(E)) time by orienting edges from lower-degree to higher-degree vertices!
TL;DR
- Use Adjacency Lists for dynamic sparse graphs ($O(V + E)$ space), Adjacency Matrices for dense small graphs ($O(1)$ edge queries), and CSR for static high-performance graph analytics.
References consulted: Programiz Graph Representations & HPC Compressed Sparse Row Architecture — referenced for verification — all content above is original.
Covered Log Update
Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue, Trie, Graph representations]