Sub topic 9
Directed Graphs: Kahn's Algorithm and Topological Order
The previous chapter found directed cycles by looking for back edges during a depth-first search. This chapter covers a second method that uses no recursion and no colors. It counts incoming edges and repeatedly removes vertices that have none. If every vertex gets removed, the graph is acyclic and the removal sequence is a valid ordering. If some vertices never get removed, the graph has a cycle.
This chapter assumes you can read Python with lists, loops, and collections.deque. It also assumes you know adjacency lists, Big-O notation, and the definition of a directed cycle from earlier chapters. Graphs here have vertices numbered 0 to n - 1, and adj[u] lists the targets of edges leaving u.
Topological Order and Why It Detects Cycles
A topological order of a directed graph is a sequence of all its vertices where every edge u → v has u appearing before v. Think of tasks and prerequisites: if task v depends on task u, then u must come first.
A directed graph has a topological order if and only if it has no directed cycle. One direction is easy to see. Suppose a cycle a → b → c → a exists. Then a must come before b, b before c, and c before a, so a comes before itself, which is impossible. The other direction is what Kahn's algorithm proves by construction: if there is no cycle, the algorithm builds an order.
So "does this graph have a cycle?" and "can this graph be topologically sorted?" are the same question. Kahn's algorithm answers both at once.
The Peeling Idea
The in-degree of a vertex is the number of edges pointing into it. A vertex with in-degree zero is called a source. Nothing has to come before a source, so it can safely go first.
Kahn's algorithm works like this:
- Compute the in-degree of every vertex.
- Put every source into a queue.
- Take a vertex
ufrom the queue and append it to the output. For each edgeu → v, decrementv's in-degree, becauseuis no longer a pending prerequisite. Ifvreaches zero, enqueue it. - Repeat until the queue is empty.
- If the output contains all
nvertices, there is no cycle. Otherwise there is one.
Why leftover vertices imply a cycle
When the queue empties early, every remaining vertex still has in-degree at least one. Those counts only include edges from other remaining vertices, because edges from removed vertices were already subtracted. Pick any remaining vertex and step backward along one of its incoming edges. That edge leads to another remaining vertex, which also has an incoming edge from a remaining vertex, and so on. There are only finitely many remaining vertices, so this backward walk must eventually revisit one. That repeated vertex closes a directed cycle.
Why an acyclic graph is fully removed
Every non-empty DAG has at least one source. If the walk-backward argument above never repeats a vertex, it must end somewhere, and that end point has no incoming edges. After removing a source, the rest of the graph is still a DAG, so it has a source too. By induction, every vertex is removed.
Implementation
The core detector from the spine is short:
from collections import deque
def has_cycle_kahn(adj):
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(u for u in range(n) if indegree[u] == 0)
removed = 0
while queue:
u = queue.popleft()
removed += 1
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return removed < nIn practice you usually want the order itself, or the stuck vertices when there is a cycle. This version returns both:
from collections import deque
def kahn_order(adj):
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(u for u in range(n) if indegree[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
leftover = [u for u in range(n) if indegree[u] > 0]
return order, leftover
cyclic = [[1, 5], [2], [3], [1, 4], [], []]
print(kahn_order(cyclic)) # ([0, 5], [1, 2, 3, 4])
acyclic = [[1, 5], [2], [3], [4], [], []]
print(kahn_order(acyclic)) # ([0, 1, 5, 2, 3, 4], [])A vertex is left over exactly when its in-degree is still positive at the end. Any vertex whose count reached zero was enqueued and then removed.
Worked Trace
The cyclic graph above has edges 0→1, 0→5, 1→2, 2→3, 3→1, and 3→4. The cycle is 1 → 2 → 3 → 1.
Initial in-degrees are [0, 2, 1, 1, 1, 1]. Vertex 1 has two incoming edges, from 0 and from 3.
| Step | Removed | In-degree changes | Queue after step |
|---|---|---|---|
| start | none | none | [0] |
| 1 | 0 | 1: 2→1, 5: 1→0 | [5] |
| 2 | 5 | none (no out-edges) | [] |
The queue is empty after two removals, but n = 6. In-degrees end as [0, 1, 1, 1, 1, 0], so vertices 1, 2, 3, and 4 are left over. Vertex 1 is stuck because its edge from 3 is never released, and 3 is stuck because it waits on 2, which waits on 1.
If you need just the cyclic part, you can run the same peeling in reverse on the leftover subgraph: repeatedly remove vertices with no outgoing edges to other leftover vertices. That strips downstream vertices like 4 and leaves the vertices that lie on cycles, plus any vertices on paths between cycles. To get one concrete cycle as a vertex list, use the parent-pointer reconstruction covered in the next chapter, or walk backward from any leftover vertex along leftover predecessors until a vertex repeats.
Edge Cases
Kahn's algorithm handles the awkward inputs from earlier chapters without special code:
- Self-loop
u → u: the edge adds one tou's own in-degree. Onlyucould decrement it, anduis never removed, souis correctly left over. - Parallel edges: two edges
u → vadd two tov's in-degree. Removinguiterates over both entries inadj[u]and subtracts two. The counts stay consistent as long as the in-degree pass and the decrement pass read the same lists. - Disconnected graphs: every source in every component goes into the initial queue, so no outer loop over start vertices is needed.
- Isolated vertices: they have in-degree zero and are removed immediately. They must still appear in
adjas empty lists, ornwill be wrong.
Common Errors
- Comparing against the wrong count. The check is
removed < nover all vertices. If you buildnfrom the keys of a dictionary that only contains vertices with outgoing edges, sinks vanish and the check breaks. - Adding a visited set. Kahn's algorithm doesn't need one. A vertex enters the queue exactly once, at the moment its count hits zero. A visited check usually hides a bug in how in-degrees were computed.
- Deduplicating edges in one pass only. If you convert
adj[u]to a set when counting but iterate the raw list when decrementing, parallel edges drive counts negative or leave them positive. - Running it on an undirected graph. An undirected edge stored in both directions gives every non-isolated vertex in-degree at least one, so almost everything looks cyclic. Use parent-aware DFS or union-find for undirected graphs.
Choosing the Queue
The proof never uses the order in which sources are taken. A FIFO queue, a stack, or a priority queue all produce valid topological orders and the same cycle verdict. A min-heap (heapq) gives the lexicographically smallest topological order, which is useful when output must be deterministic, for example when listing build steps. That costs O(V log V + E) instead of O(V + E).
Kahn's Algorithm Versus Three-Color DFS
Both run in O(V + E) time with O(V) extra memory. They differ in what they produce and how they fail.
| Concern | Kahn's algorithm | Three-color DFS |
|---|---|---|
| Recursion | None | Recursive unless rewritten iteratively |
| Output on success | Topological order directly | Reverse postorder gives an order |
| Output on cycle | Leftover vertices (cycle plus downstream) | A back edge, easy to turn into one exact cycle |
| Early exit | Must finish peeling to know | Stops at the first back edge |
| Needs in-degrees | Yes, one extra pass | No |
| Parallel scheduling | Natural: each queue snapshot is a batch of independent tasks | Not natural |
Choose Kahn's algorithm when you need the order anyway, want to avoid recursion limits, or want to group tasks into stages that can run in parallel. Choose three-color DFS when you need to show the user one specific cycle.
Exercise
Run kahn_order on adj = [[1], [2], [0], [0]]. What are order and leftover, and which leftover vertices are actually on a cycle?
Show answer
In-degrees are [2, 1, 1, 0]. Only vertex 3 is a source. Removing it drops vertex 0's in-degree from 2 to 1, which is not zero, so the queue empties. order is [3] and leftover is [0, 1, 2]. All three leftover vertices lie on the cycle 0 → 1 → 2 → 0. Vertex 3 points into the cycle, but it is upstream, so it gets removed.
Exercise
A colleague builds in-degrees with indegree[v] = 1 instead of indegree[v] += 1. Give a small acyclic graph where this makes hascyclekahn give the wrong verdict, and explain why.
Show answer
Use adj = [[2], [2], []] with edges 0→2 and 1→2. The buggy count gives vertex 2 an in-degree of 1 instead of 2. Removing 0 drops it to 0, so 2 is enqueued. Removing 1 then drops it to -1. All three vertices are removed, so this case happens to report no cycle, which is correct by luck. Now add a cycle that feeds into 2: adj = [[2], [2], [], [4], [3, 2]]. Vertex 2's true in-degree is 3 but the bug records 1. Removing 0 drops it to 0, and 2 is removed even though it depends on the cycle 3 ↔ 4. The verdict is still "cycle", because 3 and 4 are left over, but the leftover set wrongly omits 2. With different edge orders the bug can also release cycle vertices early. Counting every edge is what makes the proof work.
Exercise
Why does Kahn's algorithm need no outer loop over start vertices, while DFS-based detection does?
Show answer
DFS starts from one vertex and only reaches what is reachable from it, so it must restart from every unvisited vertex. Kahn's algorithm seeds the queue with every in-degree-zero vertex in the whole graph at once. Every vertex that can ever be removed is reachable from those seeds through decrements, whatever component it is in.