16. Topological Sort (Kahn’s Algorithm)
Order the nodes of a directed acyclic graph so every edge points forward. Used for build systems, course prerequisites and task scheduling.
How it works
An edge X -> Y means X must come before Y. Kahn’s algorithm counts each node’s incoming edges (its indegree). Nodes with indegree 0 have no prerequisites, so they go in a queue. Take one, append it to the order, and decrement the indegree of everything it points to; any node that reaches 0 joins the queue.
If the order ends up shorter than the number of nodes, some nodes never reached indegree 0: the graph has a cycle and no valid order exists.
Diagram
graph LR
A --> B
A --> C
B --> D
B --> E
C --> D
D --> F
E --> F
Step-by-step trace
Input: Read A --> B as ‘A must happen before B’. Queue processed in FIFO order.
| Step | Take | Indegree updates | Queue after | Order so far |
|---|---|---|---|---|
| start | - | indegrees: A=0, B=1, C=1, D=2, E=1, F=2 | [A] | [] |
| 1 | A | B: 1 -> 0 (ready); C: 1 -> 0 (ready) | [B, C] | [A] |
| 2 | B | D: 2 -> 1; E: 1 -> 0 (ready) | [C, E] | [A, B] |
| 3 | C | D: 1 -> 0 (ready) | [E, D] | [A, B, C] |
| 4 | E | F: 2 -> 1 | [D] | [A, B, C, E] |
| 5 | D | F: 1 -> 0 (ready) | [F] | [A, B, C, E, D] |
| 6 | F | none | [] | [A, B, C, E, D, F] |
Result: One valid order: [A, B, C, E, D, F]. Other orders can also be valid.
Complexity
| Operation | Time | Space |
|---|---|---|
| Kahn’s algorithm | O(V + E) | O(V) |
| DFS-based (reverse postorder) | O(V + E) | O(V) |
Python reference implementation
def topological_sort(graph):
"""Kahn's algorithm. graph: {node: [nodes that depend on it]}.
Returns an order, or raises ValueError if there is a cycle."""
indegree = {n: 0 for n in graph}
for n in graph:
for m in graph[n]:
indegree[m] += 1
queue = deque(n for n in graph if indegree[n] == 0)
order = []
while queue:
n = queue.popleft()
order.append(n)
for m in graph[n]:
indegree[m] -= 1
if indegree[m] == 0:
queue.append(m)
if len(order) != len(graph):
raise ValueError("graph has a cycle")
return order
Common mistakes and tips
- Always check
len(order) == number_of_nodesto detect cycles (course schedule problems). - Nodes with no edges at all still need to appear in the indegree map.
- Use a min-heap instead of a queue to get the lexicographically smallest order.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Dijkstra’s Shortest Path | Next: Union-Find (Disjoint Set Union) |