Mental model
Build steps, course prerequisites, spreadsheet formulas, package dependencies: all are tasks with
"must happen before" constraints. Draw each task as a node and each constraint "a before b" as an
edge a → b. A topological order is a list of all nodes in which every edge points forward:
for every edge a → b, a comes earlier than b.
Such an order exists exactly when the graph has no directed cycle (a DAG, directed acyclic
graph). If a → b → c → a, then a must precede itself: impossible. Conversely, every DAG has at
least one node with no incoming edge (otherwise you could walk backwards forever, and with finitely
many nodes you would repeat one: a cycle), and that observation is the whole algorithm.
The number of incoming edges of a node is its in-degree. A node with in-degree 0, a source, waits for nothing, so it can go first. Remove it and its outgoing edges, and the rest of the graph is still a DAG with new sources. Repeat until nothing is left.
Kahn’s algorithm
kahn(n, edges):
indegree = [0] * n
for (u, v) in edges: adj[u].append(v); indegree[v] += 1
queue = [v for v in 0..n-1 if indegree[v] == 0] # ascending
order = []
while queue not empty:
u = queue.dequeue()
order.append(u)
for v in adj[u]: # ascending
indegree[v] -= 1 # "remove" edge u → v
if indegree[v] == 0: queue.enqueue(v)
return order, len(order) < n # True = cycle
Nothing is deleted from the graph. "Removing" an edge just decrements the in-degree of its target,
so indegree[v] always means "incoming edges from nodes not yet output". The lab shows that number
as each node's tag, draws removed edges dashed, and keeps the queue and the order built so far as
two rows in front of the graph. Step through the Course plan preset: 4 and 5 start with in-degree
0, so they go first; outputting 5 frees 0 and 2, and so on, giving 4 5 0 2 3 1.
Why the output is valid. A node is enqueued only when its in-degree is 0, that is, after every
node with an edge into it has been output. So for every edge u → v, u is output before v is
even enqueued.
Why leftovers mean a cycle. Suppose the queue empties with some nodes never output. Each of them still has in-degree > 0, and its remaining incoming edges come from other nodes that were never output (output nodes have had their edges removed). So from any leftover node you can step backwards along an edge to another leftover node, forever. With finitely many nodes, that backward walk repeats a node, and the repeated stretch is a directed cycle. The lab does exactly that walk at the end of the Cycle: no order preset and names the cycle 1 → 2 → 3 → 1.
Not every leftover node lies on a cycle. In that preset, node 4 only depends on 3, but 3 is stuck, so 4 is stuck behind it. Kahn's algorithm reports "no order"; finding which nodes form cycles (strongly connected components) is a separate, also linear-time, problem.
Ties: which order do you get?
Most DAGs have many topological orders. In Build steps, nodes 0 and 1 are both sources, and either could come first. Which one Kahn's algorithm outputs depends only on how the waiting nodes are picked:
- FIFO queue, sources and successors in ascending order (this lesson and its code): reproducible, roughly "level by level".
- Stack instead of queue: also valid, a different order, tends to finish one chain before starting another.
- Min-heap: always output the smallest available node. The result is the lexicographically smallest topological order, at O((V + E) log V) instead of O(V + E). Use this when a problem asks for "the smallest" valid order.
All three are correct. Do not compare an order against a single expected answer unless the tie-break is specified; compare against the definition (every edge points forward) instead, which is what the randomized tests here do.
Cost: O(V + E)
| Phase | Work |
|---|---|
| Build adjacency lists and count in-degrees | one step per edge: O(E), plus O(V) to allocate |
| Queue the sources | one check per node: O(V) |
| Main loop | each node is dequeued at most once (O(V)); each edge is "removed" once, when its source is output (O(E)) |
Total O(V + E) time and O(V + E) space for the lists, in-degrees and queue. The Edge steps metric in the lab counts every edge twice for an acyclic graph: once while counting, once while removing. In the cycle case, edges out of stuck nodes are counted but never removed. (This implementation sorts each adjacency list to fix the neighbour order, which adds an O(E log E) term in the worst case; with input already in order, or without the determinism requirement, it is not needed.)
Kahn’s algorithm or DFS?
The other classic method runs DFS over all nodes and outputs nodes in reverse finish order: a node finishes only after everything it points to has finished, so reversing puts it before them. A back edge to a gray node during that DFS signals a cycle (see the BFS and DFS lesson).
| Kahn | DFS finish order | |
|---|---|---|
| Time | O(V + E) | O(V + E) |
| Cycle detection | leftovers after the queue empties | a back edge |
| Recursion | none | depth up to V (or an explicit stack) |
| Natural extras | process "levels" or parallel batches; easy smallest-first variant with a heap | fits naturally into other DFS-based algorithms (e.g. strongly connected components) |
Kahn's algorithm is the usual choice for schedulers and build tools because it is iterative and exposes, at every moment, the set of tasks that are ready to run.
Built-in support
- Python:
graphlib.TopologicalSorter(standard library since 3.9).static_order()yields a topological order and raisesCycleError(with a cycle in its arguments) if there is none;prepare(),get_ready()anddone()expose the ready set for parallel processing, the same idea as Kahn's queue. The Python tests here check their cycle verdict against it. - C#, Java, C++: no topological sort in the standard library. Build it from
Queue<int>/ArrayDeque<Integer>/std::queue<int>, or fromPriorityQueue/std::priority_queuefor the smallest-first variant. (Java'sPriorityQueueand C#'sPriorityQueue<TElement, TPriority>are min-heaps by default; C++'sstd::priority_queueis a max-heap unless you passstd::greater<>.)
The teaching implementation
Kahn/kahn takes the node count and the edge list, sorts each adjacency list, and returns the
nodes output in order together with a HasCycle flag (order.Count < n). Returning the partial
order instead of throwing keeps the cycle case inspectable: the nodes missing from it are exactly
the stuck ones.
All four languages run one shared fixture with exact expected orders (chains, a diamond, the course plan, ties, a graph with no edges, a single node, and three kinds of cycle: the whole graph, a cycle after a valid prefix, and a separate cycle next to a valid part). They also run 600 random graphs, about a third of them allowed to contain cycles: the cycle verdict is compared with brute-force source removal, and every returned order is checked edge by edge.
Common mistakes
- Counting out-degrees instead of in-degrees, or decrementing the source instead of the target.
- Enqueueing a node more than once by checking
indegree[v] <= 0or by re-scanning all nodes each round (which also makes the algorithm O(V²)). - Forgetting the cycle check. Without comparing
order.lengthwithn, a cyclic graph silently yields a partial order that looks like an answer. - Treating the order as unique and testing against one expected list.
- Edges in the wrong direction. "a depends on b" means
b → a; decide once and say it out loud.
Edge cases
- No edges: every node is a source; with ascending seeding the order is 0, 1, …, n − 1.
- A single node: the order is that node.
- No sources at all: the queue starts empty, nothing is output, and every node is left over (three-cycle in the fixture).
- Two separate parts, one cyclic: the acyclic part is output, the cyclic part is left over.
- Opposite edges
a → bandb → a: a cycle of length 2.
Worked practice
1. Edges 0 → 2, 1 → 2, 2 → 3, 1 → 3. Run Kahn's algorithm with ascending tie-breaks.
Answer
In-degrees: 0:0, 1:0, 2:2, 3:2. Queue 0, 1. Output 0 (2 drops to 1). Output 1 (2 drops to 0 and is enqueued; 3 drops to 1). Output 2 (3 drops to 0, enqueued). Output 3. Order: 0 1 2 3.
2. Add the edge 3 → 1 to that graph. What happens?
Answer
Now 1 has in-degree 1, so only 0 is a source. Output 0 (2 drops to 1). The queue is empty with 1, 2 and 3 left over (in-degrees 1, 1 and 2). Walking backwards from 1: 3 → 1, then 2 → 3, then 1 → 2, so 1 → 2 → 3 → 1 is a cycle (and so is 1 → 3 → 1). No topological order exists.
3. How many topological orders does a graph with n nodes and no edges have, and which one does this implementation return?
Answer
n!, since any permutation is valid. This implementation queues the sources in ascending order, so it returns 0, 1, …, n − 1.
4. You must schedule build steps on 4 machines, running every step as soon as its dependencies finish. How does Kahn's algorithm help?
Answer
The queue is the set of steps whose dependencies are all done. Take up to 4 steps from it, run them,
and when each finishes, decrement its successors' in-degrees and enqueue any that reach 0. That is
Kahn's algorithm with the dequeues spread over time, exactly what graphlib's get_ready() and
done() provide.
Summary
- A topological order puts every edge
u → vwithubeforev; it exists iff the graph is a DAG. - Kahn's algorithm outputs nodes whose in-degree has dropped to 0 and decrements their successors.
- If fewer than n nodes come out, the leftovers contain a cycle; walking backwards among them finds one.
- O(V + E) time and space. The tie-break (queue, stack, min-heap) picks one of many valid orders.
- DFS reverse finish order is the main alternative; Python ships
graphlib.TopologicalSorter.