Sub topic 1
Representing Graphs for Cycle Detection
Every cycle detection algorithm in this tutorial reads a graph from one of two structures: an edge list or an adjacency list. Choosing the right structure, and storing the right details in it, decides whether later algorithms handle tricky inputs correctly.
Prerequisites
This chapter assumes you know:
- Basic Python: lists, tuples, functions, and loops
- Graph vocabulary: vertices, edges, directed and undirected graphs
- Big-O notation
Vertices are numbered 0 to n - 1 throughout, so plain Python lists can be indexed by vertex.
Edge Lists
An edge list is a list of (u, v) pairs, one pair per edge. It is the simplest format and often the one input arrives in.
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (1, 2)]Edge lists work well for algorithms that look at edges one at a time, such as union-find, which you will meet later. They are a poor fit for traversal, because finding the neighbors of one vertex means scanning every edge, which costs O(E) per lookup.
Adjacency Lists
An adjacency list stores, for each vertex, the list of vertices it connects to. DFS and Kahn's algorithm both need fast neighbor lookup, so they use this format. Building it from an edge list takes O(V + E) time and space.
Directed Graphs
In a directed graph, edge (u, v) goes in only one direction, so it is stored once, under u.
def build_directed(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
return adj
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (1, 2)]
print(build_directed(4, edges))
# [[1], [2, 2], [0, 3], []]Undirected Graphs
In an undirected graph, edge (u, v) can be walked both ways, so it is stored twice, once under each endpoint. This creates a problem. When DFS walks from u to v, it sees u again among v's neighbors, and that looks like a cycle even though it is the same edge. To tell "the edge I just used" apart from "a different edge to the same vertex", give each edge an ID and store it with the neighbor.
def build_undirected(n, edges):
adj = [[] for _ in range(n)]
for i, (u, v) in enumerate(edges):
adj[u].append((v, i))
adj[v].append((u, i))
return adj
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (1, 2)]
for u, nbrs in enumerate(build_undirected(4, edges)):
print(u, nbrs)
# 0 [(1, 0), (2, 2)]
# 1 [(0, 0), (2, 1), (2, 4)]
# 2 [(1, 1), (0, 2), (3, 3), (1, 4)]
# 3 [(2, 3)]Vertex 1 now lists vertex 2 twice, with edge IDs 1 and 4. Those are two distinct edges, and together they form a cycle. A list that stored only vertex numbers, or a set of neighbors, would lose that information.
Choosing a Representation
| Structure | Neighbor lookup | Best for | Watch out for |
|---|---|---|---|
| Edge list | O(E) | Union-find, streaming edges | Slow for traversal |
| Directed adjacency list | O(degree) | Three-color DFS, Kahn's algorithm | Store each edge once |
| Undirected adjacency list with edge IDs | O(degree) | Parent-aware DFS | Each edge appears twice |
A self-loop (u, u) in build_undirected appends (u, i) to adj[u] twice, both times with the same ID. A later chapter shows how edge IDs let DFS treat this correctly.
Exercise
For n = 3 and edges [(0, 1), (1, 1)], what does build_undirected return, and why does vertex 1's list contain three entries?
Show answer
It returns [[(1, 0)], [(0, 0), (1, 1), (1, 1)], []]. Edge 0 adds (0, 0) to vertex 1's list. The self-loop, edge 1, is stored under both of its endpoints, and both endpoints are vertex 1, so (1, 1) appears twice. Vertex 2 has no edges.
Exercise
Why does an undirected adjacency list built from E edges contain 2E entries, while a directed one contains E?
Show answer
An undirected edge can be traversed from either endpoint, so it is stored under both. A directed edge can only be traversed from its source, so it is stored once.