Topological sort: Kahn's algorithm and DFS finishing order
A topological order lists tasks so every dependency comes first. Kahn’s algorithm ticks in-degree counters down; DFS uses finishing order.
Before you start: Bipartite check by 2-coloring.
The idea
A course plan must take CS1 before CS2, CS2 and Math before Algo, and Algo before AI. Which order of all five keeps every rule?
Build tools, package managers and spreadsheet recalculation all solve this same ordering problem.
Intuition
Each label counts the edges coming into a node: its in-degree. Nodes 0 and 1 have in-degree 0, so nothing has to come before them.
Take a node with in-degree 0 and delete it. The rest of the graph is a smaller version of the same problem.
Complexity
Each node enters and leaves the queue once. Each edge is counted once and lowered once, so Kahn's algorithm runs in O(V + E).
The in-degree array and the queue each hold at most V entries, so the extra space is O(V).
Pitfalls
1, 2 and 3 wait on each other, so their in-degrees never reach 0, and 4 waits on 3. The queue empties early: report a cycle.
Variations
Here 0 and 1 are both ready, so two orders are valid. For the smallest order, keep ready nodes in a min-heap: 0 comes out first.
Code
Pseudocode
indeg[v] ← number of edges into v
queue ← every v with indeg[v] = 0
order ← []
while queue not empty
u ← dequeue
append u to order
for each edge u → v
indeg[v] ← indeg[v] − 1
if indeg[v] = 0: enqueue v
if order has fewer than V nodes: a cycle
return order
Python
from collections import deque
def topo_order(adj):
indeg = [0] * len(adj)
for u in range(len(adj)):
for v in adj[u]:
indeg[v] += 1
queue = deque(v for v in range(len(adj)) if indeg[v] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
if len(order) < len(adj):
return None
return order
JavaScript
function topoOrder(adj) {
const indeg = new Array(adj.length).fill(0);
for (const outs of adj) for (const v of outs) indeg[v]++;
const queue = [];
for (let v = 0; v < adj.length; v++) if (indeg[v] === 0) queue.push(v);
const order = [];
while (queue.length > 0) {
const u = queue.shift();
order.push(u);
for (const v of adj[u]) {
indeg[v]--;
if (indeg[v] === 0) queue.push(v);
}
}
if (order.length < adj.length) return null;
return order;
}
Java
List<Integer> topoOrder(List<List<Integer>> adj) {
int[] indeg = new int[adj.size()];
for (List<Integer> outs : adj) for (int v : outs) indeg[v]++;
Deque<Integer> queue = new ArrayDeque<>();
for (int v = 0; v < adj.size(); v++) if (indeg[v] == 0) queue.add(v);
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int u = queue.poll();
order.add(u);
for (int v : adj.get(u)) {
indeg[v]--;
if (indeg[v] == 0) queue.add(v);
}
}
if (order.size() < adj.size()) return null;
return order;
}
Cost at a glance
| Time | O(V + E) |
|---|---|
| Space | O(V) |
| Input | Directed acyclic graph |
| Output | Order with every edge pointing forward |
Practice problems (6)
Topological order Warm-up
Kahn's algorithm runs on this graph. It starts with the in-degree-0 nodes in number order and handles each node's edges in the order listed. Drag the nodes into the order Kahn's algorithm outputs them.
Tick the in-degree down Warm-up
Node 3 has three incoming edges: from 0, 1 and 2. Kahn's algorithm has just taken 0 from the queue. Its first edge goes to 3. What does the in-degree of 3 drop to?
From finishing order to topological order Standard
DFS ran on this graph from 0. The labels show the order the nodes finished: 4 finished first (#1) and 0 last (#5). Write the topological order DFS produces, as node numbers separated by spaces.
Course schedule II Standard
There are numCourses courses numbered 0 to numCourses − 1. Each pair [a, b] in prerequisites means course b must be taken before course a. Return an order that takes every course after its prerequisites. Any valid order is accepted. Return [] if no order exists.
Build order with dependencies Standard
Projects are numbered 0 to n − 1. An edge u → v in graph means project u must be built before project v. Return the build order. When several projects are ready, build the smallest-numbered one first, so the answer is unique. Return [] if the dependencies form a cycle.
Alien dictionary Challenge
An alien language uses lowercase English letters in an unknown order. words is sorted by that order, like a dictionary. Return a string with every letter that appears, in an order consistent with the words. Any valid order is accepted. Return "" if no order fits.
Next on the path: Shortest paths in unweighted graphs; path reconstruction