Sub topic 1
Representing Graphs for Cycle Detection
Every cycle detection algorithm in this tutorial reads a graph from some data structure. The structure you pick decides three things: how fast the algorithm runs, whether it can see self-loops and parallel edges, and how easily it can tell which edge it used to reach a vertex. This chapter sets up the representations the later chapters use. It also covers the conversion steps that cause quiet bugs when they are done wrong.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python syntax, including lists, dictionaries, functions, and loops
- Graph vocabulary: vertices, edges, directed and undirected graphs
- The idea of an adjacency list
- Big-O notation
You don't need to know any traversal algorithm yet. Depth-first search gets its own refresher chapter.
The Three Common Representations
Edge lists
An edge list is a plain list of pairs. Each pair (u, v) is one edge. Graph data often arrives in this form, for example from a file, a database table, or a list of declared dependencies.
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]An edge list stores each edge exactly once, keeps duplicates, and makes it easy to process edges one at a time. That last property is what union-find needs, because it decides about each edge as it arrives. An edge list cannot answer "who are the neighbors of vertex 2?" without scanning every edge. That makes it a poor fit for DFS.
Adjacency lists
An adjacency list gives each vertex a list of its neighbors. Vertices are numbered 0 to n - 1, and adj[u] holds the vertices reachable from u by one edge. It uses O(V + E) memory and lists the neighbors of u in O(deg(u)) time. DFS, three-color DFS, and Kahn's algorithm all depend on that.
Adjacency matrices
An adjacency matrix is an n × n grid in which M[u][v] records whether an edge goes from u to v. It answers "is there an edge u→v?" in O(1) time. It costs O(V²) memory, and a full traversal costs O(V²) time no matter how few edges exist. A boolean matrix also cannot represent parallel edges. You would have to store counts instead.
| Representation | Memory | List neighbors of u | Keeps parallel edges | Typical use in this tutorial |
|---|---|---|---|---|
| Edge list | O(E) | O(E) | Yes | Union-find, input format |
| Adjacency list | O(V + E) | O(deg(u)) | Yes | DFS, three-color DFS, Kahn's algorithm |
| Adjacency matrix | O(V²) | O(V) | Only with counts | Rarely; small dense graphs |
Building a Directed Adjacency List
In a directed graph, the edge (u, v) means u→v only, so you add it once:
def build_directed(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
return adj
adj = build_directed(4, [(0, 1), (1, 2), (2, 0), (2, 3)])
print(adj) # [[1], [2], [0, 3], []]Vertex 3 has an empty list. It must still exist, because the algorithms loop over range(len(adj)) and expect every vertex to have an entry. This is the exact format the directed algorithms in later chapters accept: a list of lists of integers.
Building an Undirected Adjacency List with Edge IDs
An undirected edge {u, v} can be crossed in both directions, so you store it in both adj[u] and adj[v]. That duplication causes trouble. A DFS that goes from u to v will find u in v's list and might report a cycle where none exists. The undirected DFS chapter fixes this by skipping the edge it arrived on. To skip the right edge, the algorithm needs an identifier for each edge, not only its endpoints.
Use the edge's position in the input list as its ID, and store (neighbor, edge_id) pairs:
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), (1, 2), (3, 3)]
adj = build_undirected(4, edges)
for u, neighbors in enumerate(adj):
print(u, neighbors)Output:
0 [(1, 0)]
1 [(0, 0), (2, 1), (2, 2)]
2 [(1, 1), (1, 2)]
3 [(3, 3), (3, 3)]This small example contains two tricky structures:
- Parallel edges. Edges 1 and 2 both join vertices 1 and 2. Their IDs differ, so an algorithm can tell them apart. Two distinct edges between the same pair form a cycle of length 2. If you identified edges only by the parent vertex, you would skip both and miss that cycle.
- A self-loop. Edge 3 joins vertex 3 to itself. Because
u == v, the builder appends it toadj[3]twice, with the same ID both times. This is correct. It matches the convention that a self-loop adds 2 to the vertex's degree, and code that skips by edge ID treats both entries consistently.
The edge-cases chapter shows how the detection algorithms handle each of these. For now, the point is that the representation keeps the information they need.
Converting Named Vertices to Integers
Real inputs rarely use integers. Package names, task IDs, and lock names are strings. Map them to dense integers 0..n-1 first, run the algorithm on integers, and translate results back:
def index_vertices(named_edges, extra_vertices=()):
ids = {}
def get(name):
if name not in ids:
ids[name] = len(ids)
return ids[name]
for name in extra_vertices:
get(name)
edges = [(get(a), get(b)) for a, b in named_edges]
names = [None] * len(ids)
for name, i in ids.items():
names[i] = name
return edges, names
deps = [("app", "web"), ("web", "http"), ("http", "app")]
edges, names = index_vertices(deps, extra_vertices=["docs"])
adj = [[] for _ in range(len(names))]
for u, v in edges:
adj[u].append(v)
print(names) # ['docs', 'app', 'web', 'http']
print(adj) # [[], [2], [3], [1]]The extra_vertices parameter exists for vertices that have no edges. A vertex that appears in no edge never gets an ID, so it disappears from the graph. Missing isolated vertices doesn't change whether a cycle exists. It does break algorithms that count vertices, such as Kahn's algorithm, which compares the number of removed vertices to n, and it hides nodes from reports.
Dictionary-Based Graphs and the Missing-Key Bug
Many codebases store graphs as dict[str, list[str]]. A common bug comes from vertices that appear only as targets:
graph = {"a": ["b"], "b": ["c"]} # "c" has no keyCode that does graph[v] for every neighbor raises KeyError on "c". Code that loops over graph to count in-degrees or to start DFS from every vertex skips "c" entirely. Normalize the graph before you use it:
def normalize(graph):
full = {u: list(vs) for u, vs in graph.items()}
for vs in graph.values():
for v in vs:
full.setdefault(v, [])
return full
print(normalize({"a": ["b"], "b": ["c"]}))
# {'a': ['b'], 'b': ['c'], 'c': []}Common Representation Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `[[]] * n` for adjacency | Every vertex shares neighbors; false cycles | `[[] for _ in range(n)]` |
| Adding undirected edges once | DFS misses half the connections | Append to both endpoints |
| Adding directed edges twice | Every edge looks like a 2-cycle | Append only to `adj[u]` |
| Deduplicating edges with a set | Parallel-edge cycles vanish | Keep duplicates; use edge IDs |
| Dropping isolated or target-only vertices | `KeyError`, wrong vertex counts | Normalize and include all vertices |
| Boolean adjacency matrix for a multigraph | Parallel edges collapse into one | Use lists or store counts |
Exercises
Exercise
You call build_undirected(3, [(0, 1), (0, 1), (2, 2)]). Write out adj, and say which structures in this graph form cycles.
Show answer
adj[0] = [(1, 0), (1, 1)], adj[1] = [(0, 0), (0, 1)], adj[2] = [(2, 2), (2, 2)]. The two parallel edges between 0 and 1 (IDs 0 and 1) form a cycle of length 2, and the self-loop on vertex 2 (ID 2) is a cycle of length 1. Distinct edge IDs keep the parallel edges apart, and the self-loop shows up twice with the same ID.
Exercise
A colleague builds a directed graph with build_undirected because "it has more information," then runs a directed cycle detector on it. The input is the chain 0→1→2. What happens, and why?
Show answer
Every edge is stored in both directions, so the directed algorithm sees 0→1 and 1→0 and reports a cycle, even though the chain is acyclic. A directed detector would also fail on the (neighbor, edge_id) tuples unless it unpacked them. Directed graphs must be built with one entry per edge.
Exercise
Given graph = {"x": ["y", "z"], "y": ["z"]}, how many vertices should a Kahn-style algorithm count, and what goes wrong if you use len(graph) without normalizing?
Show answer
Three vertices: x, y, and z. len(graph) is 2 because z has no key. In-degree counting would then hit a KeyError on z or skip it, and comparing removed vertices to n would give the wrong answer. normalize(graph) adds "z": [] and fixes both problems.