A topological order of a directed graph is a linear listing of nodes where every edge points forward: for each edge u → v, u appears before v. It is the mathematical form of "do things in an order that respects dependencies", course prerequisites, build systems compiling files, spreadsheets recalculating cells, package managers installing libraries, CI/CD pipeline stages.
A valid order exists if and only if the graph is a DAG, a directed acyclic graph. Any cycle is a genuine contradiction (A needs B, B needs C, C needs A), and no ordering can satisfy it. Both algorithms below therefore do double duty: they either produce an order or prove none can exist, which is why build tools report "circular dependency" with such confidence.
Kahn's algorithm (BFS with in-degrees)
- 1
Count in-degrees
For every node, count incoming edges. Nodes with in-degree 0 depend on nothing, they are immediately schedulable.
- 2
Seed a queue
Push all in-degree-0 nodes. Their relative order among themselves is arbitrary, every choice leads to a valid order.
- 3
Process and peel
Pop a node, append it to the order, and delete its outgoing edges: each child's in-degree drops by 1. Any child reaching in-degree 0 joins the queue.
- 4
Verify
If the final order contains fewer than V nodes, a cycle swallowed the rest, the nodes never reaching in-degree 0 form (or sit behind) the cycle. Report it; don't guess.
Kahn's algorithm
function topoSort(nodes, edges) { // edges: [u, v][] meaning u before v
const adj = new Map(nodes.map((n) => [n, []]));
const indeg = new Map(nodes.map((n) => [n, 0]));
for (const [u, v] of edges) {
adj.get(u).push(v);
indeg.set(v, indeg.get(v) + 1);
}
const queue = nodes.filter((n) => indeg.get(n) === 0);
const order = [];
while (queue.length > 0) {
const u = queue.shift();
order.push(u);
for (const v of adj.get(u)) {
indeg.set(v, indeg.get(v) - 1); // "remove" edge u → v
if (indeg.get(v) === 0) queue.push(v); // v's prerequisites are done
}
}
return order.length === nodes.length
? order // valid topological order
: null; // cycle detected
}Cost summary
| Operation / case | Cost | Notes |
|---|---|---|
| Kahn's algorithm | O(V + E) | each node and edge processed once |
| DFS reverse post-order | O(V + E) | elegant alternative: finish times reversed give a valid order |
| Cycle detection | included | order shorter than V ⇔ cycle exists |
The order is generally NOT unique. If a problem requires the lexicographically smallest order, run Kahn's with a min-heap instead of a FIFO queue.
Practice
Edges: A→B, A→C, B→D, C→D. Which node MUST appear first in every topological order, and which last?
Reveal explanation
A is the only node with in-degree 0 (nothing precedes it), so every valid order starts with A. D has in-degree 2 and no outgoing edges, so it is always last. B and C may swap: A-B-C-D and A-C-B-D are both valid.