Sub topic 1
Representing a Graph as an Adjacency List
Every algorithm in this tutorial starts from the same place: a graph stored in memory so that, given a vertex, you can list its neighbors quickly. Breadth-first search, depth-first search, Kosaraju's algorithm, and Tarjan's algorithm all spend most of their time asking "who is next to this vertex?" The adjacency list answers that question in time proportional to the number of neighbors. That property is why traversal-based component labeling runs in O(V + E).
This chapter shows how to build an adjacency list from an edge list, how the undirected and directed cases differ, and which mistakes quietly corrupt the graph before any algorithm runs.
Prerequisites
This chapter assumes you are comfortable with:
- Python lists, list comprehensions, loops, functions, and dictionaries.
- Basic graph vocabulary: a vertex (node), an edge (a connection between two vertices), and the difference between directed and undirected edges.
- Big-O notation, enough to read O(V + E) and O(V²). V is the number of vertices and E is the number of edges.
You do not need any graph library. Everything here uses plain Python.
The Input: An Edge List
Graph data usually arrives as an edge list, which is a sequence of pairs (u, v) where each pair means "u and v are connected." Files, database tables, and problem statements on coding sites nearly always use this format, because it is compact and easy to write.
n = 6
edges = [(0, 1), (1, 2), (3, 4)]The value n matters as much as the edges do. Vertex 5 appears in no edge, but it is still part of the graph. It is an isolated vertex, and later it will form a connected component of its own. If you infer the vertex set only from the edges, vertex 5 disappears and every component count you compute will be wrong.
An edge list is bad for traversal. To find the neighbors of vertex 1, you have to scan every edge, which costs O(E) per lookup. A full traversal would then cost O(V · E). The adjacency list fixes this by grouping edges by endpoint once, up front.
Building the Adjacency List
An adjacency list is a list indexed by vertex, where entry u holds the vertices adjacent to u. In an undirected graph, the edge (u, v) means v is a neighbor of u and u is a neighbor of v, so each edge is stored twice.
def build_adjacency(n, edges, directed=False):
adj = [[] for _ in range(n)]
for u, v in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"edge ({u}, {v}) has a vertex outside 0..{n - 1}")
adj[u].append(v)
if not directed:
adj[v].append(u)
return adj
edges = [(0, 1), (1, 2), (3, 4)]
adj = build_adjacency(6, edges)
for u, neighbors in enumerate(adj):
print(u, neighbors)
# 0 [1]
# 1 [0, 2]
# 2 [1]
# 3 [4]
# 4 [3]
# 5 []Building the list takes O(V + E) time: O(V) to create the empty lists and O(1) amortized per edge to append. The structure holds V lists and 2E neighbor entries for an undirected graph, or E entries for a directed one.
Directed Graphs
For a directed graph, the edge (u, v) means you can go from u to v but not back, so only adj[u] gets the entry:
print(build_adjacency(6, [(0, 1), (1, 2), (3, 4)], directed=True))
# [[1], [2], [], [4], [], []]Kosaraju's algorithm, covered later, needs the reversed graph as well. You build it in the same loop by appending u to radj[v]. Keeping both lists costs twice the memory but lets you follow edges in either direction in O(1) per edge.
Common Errors
Shared Inner Lists
This is the most common bug, and Python raises no error for it:
bad = [[]] * 3
bad[0].append(1)
print(bad) # [[1], [1], [1]]
good = [[] for _ in range(3)]
good[0].append(1)
print(good) # [[1], [], []][[]] * 3 creates one list and stores three references to it. Every vertex then shares the same neighbor list, so the whole graph looks like a single component. Always use a comprehension.
Forgetting the Reverse Edge
If you store an undirected edge only as adj[u].append(v), a traversal starting from v cannot reach u. Then the component label depends on which vertex the search starts from. Results like that look plausible on small tests and fail on real data. When the input is undirected, append both directions.
Dropping Isolated Vertices
Code that computes n = max(max(u, v) for u, v in edges) + 1 misses isolated vertices with high indices and crashes on an empty edge list. Take n from the input specification whenever you can.
Self-Loops and Duplicate Edges
A self-loop (2, 2) in an undirected graph appends 2 to adj[2] twice. A repeated edge (0, 1), (0, 1) puts 1 into adj[0] twice. Neither one changes which vertices are connected, so component algorithms still return correct results, because they check a visited flag before enqueuing a vertex. What changes is degree counts and the "2E entries" size estimate. If you need a simple graph, deduplicate:
def build_simple_adjacency(n, edges):
nbrs = [set() for _ in range(n)]
for u, v in edges:
if u == v:
continue
nbrs[u].add(v)
nbrs[v].add(u)
return [sorted(s) for s in nbrs]
print(build_simple_adjacency(4, [(0, 1), (1, 0), (2, 2), (1, 3)]))
# [[1], [0, 3], [], [1]]Sets cost more memory per entry than lists. Deduplicate only when duplicates actually affect your result.
Vertices That Are Not Integers
Real data names vertices with strings, IDs, or coordinates. Map each name to a dense index from 0 to n−1 first, then build the integer adjacency list. Dense indices let you use flat lists for visited and label arrays instead of dictionaries. Flat lists are faster and use less memory.
def build_from_labels(edges, isolated=()):
index = {}
def idx(name):
if name not in index:
index[name] = len(index)
return index[name]
pairs = [(idx(a), idx(b)) for a, b in edges]
for name in isolated:
idx(name)
adj = [[] for _ in range(len(index))]
for u, v in pairs:
adj[u].append(v)
adj[v].append(u)
names = list(index)
return adj, names, index
adj, names, index = build_from_labels(
[("alice", "bob"), ("bob", "carol"), ("dave", "erin")],
isolated=["frank"],
)
print(names) # ['alice', 'bob', 'carol', 'dave', 'erin', 'frank']
print(adj) # [[1], [0, 2], [1], [4], [3], []]Keep names so you can translate component labels back to the original identifiers. Python dictionaries preserve insertion order, so names[i] is the vertex that received index i.
A defaultdict(list) keyed by name also works and skips the mapping step. Its weakness is isolated vertices: a vertex with no edges never becomes a key unless you add it explicitly. That reproduces the dropped-vertex bug from earlier.
Choosing a Representation
| Representation | Space | List neighbors of u | Test if edge (u, v) exists | Good fit |
|---|---|---|---|---|
| Edge list | O(E) | O(E) | O(E) | Storage, input, union-find |
| Adjacency list | O(V + E) | O(deg(u)) | O(deg(u)) | BFS, DFS, SCC algorithms |
| Adjacency matrix | O(V²) | O(V) | O(1) | Small, dense graphs |
For connected components, the adjacency list is the right default. Traversal touches each neighbor list once, so the total work is the sum of all degrees, which is 2E, plus V. An adjacency matrix forces O(V²) work even when the graph is sparse. With a million vertices, that is 10¹² cells.
The edge list keeps one important use. Union-find, covered in a later chapter, processes edges one at a time and never needs neighbor lookups. It can work directly on the raw edge list, without building an adjacency structure at all.
Exercises
Exercise
Given n = 4 and the directed edges [(0, 1), (2, 1), (1, 3)], what do build_adjacency(4, edges, directed=True) and the reversed adjacency list radj look like?
Show answer
adj = [[1], [3], [1], []]. In radj, each edge (u, v) puts u into radj[v], so radj = [[], [0, 2], [], [1]].
Exercise
A teammate builds the adjacency list with adj = [[]] * n and reports that every graph they test has exactly one connected component. Explain the cause.
Show answer
[[]] * n stores n references to the same list object. Every append goes into that one shared list, so every vertex appears to have every neighbor, and any traversal reaches all vertices from any start. The fix is adj = [[] for _ in range(n)].
Exercise
An undirected graph has V = 10 vertices and E = 15 edges, including one self-loop and no duplicate edges. How many total neighbor entries does build_adjacency store, and does the self-loop change the connected components?
Show answer
Each edge adds two entries, including the self-loop, which adds its vertex to its own list twice. That gives 2 × 15 = 30 entries. A self-loop connects a vertex only to itself, so it does not change the components.
Exercise
Why does buildfromlabels take an isolated parameter instead of deriving all vertices from the edges?
Show answer
A vertex with no edges never appears in the edge list, so deriving vertices from edges would drop it. That would give it no index and leave its single-vertex component out of every count.