Topological
Sort
Order the vertices of a DAG so every directed edge (u → v) has u before v. Used for task scheduling, build systems, course prerequisites, and spreadsheet evaluation.
What is topological sort?
Topological sort orders the nodes of a directed acyclic graph (DAG) so that every edge points forward: each task comes after everything it depends on. It answers questions like "in what order should I take these courses?" or "in what order should these packages build?". Kahn's algorithm repeatedly takes nodes with no remaining prerequisites, in O(V + E).
function topoSort(deps) { // deps: { task: [prerequisites] }
const indeg = {}, next = {};
for (const [t, pre] of Object.entries(deps)) {
indeg[t] ??= 0;
for (const p of pre) { indeg[t]++; (next[p] ??= []).push(t); indeg[p] ??= 0; }
}
const queue = Object.keys(indeg).filter((t) => indeg[t] === 0), order = [];
while (queue.length) {
const t = queue.shift(); order.push(t);
for (const n of next[t] ?? []) if (--indeg[n] === 0) queue.push(n);
}
if (order.length !== Object.keys(indeg).length) throw new Error("cycle!");
return order;
}
topoSort({ css: ["html"], js: ["html"], react: ["js", "css"] }); // html, css, js, reactKahn's BFS — animated
// Array state
// Pseudocode
Algorithm walkthrough
Compute in-degrees
For every edge (u → v), increment in-degree[v]. Nodes with in-degree 0 have no prerequisites — they can be processed first.
Kahn's algorithm
1// Kahn's algorithm — BFS topological sort2function topoSort(graph):3 inDegree = {v: 0 for all v}4 for u in graph:5 for v in graph[u]: inDegree[v]++6 queue = [v for v where inDegree[v] == 0]7 result = []8 while queue not empty:9 u = queue.dequeue()10 result.append(u)11 for v in graph[u]:12 inDegree[v]--13 if inDegree[v] == 0:14 queue.enqueue(v)15 if len(result) != len(graph):16 return 'CYCLE DETECTED'17 return result // O(V+E)
DFS post-order variant
1// DFS post-order topological sort2function topoSortDFS(graph):3 visited = Set()4 result = Stack()5 for v in graph:6 if v not in visited:7 dfs(v, visited, result)8 return result.reversed()910function dfs(v, visited, stack):11 visited.add(v)12 for neighbor in graph[v]:13 if neighbor not in visited:14 dfs(neighbor, visited, stack)15 stack.push(v) // add AFTER all descendants
Complexity
Linear time
Linear time
🎯 Quick Check
You run Kahn's algorithm on a graph of 5 nodes and get a result of length 4. What does this tell you?
Topological Sort: summary
Key points
- It only exists for DAGs; if there's a cycle, no valid order exists.
- There can be several valid orders.
- The DFS alternative: add each node to the result after visiting its descendants, then reverse.
Frequently asked questions
›Where is topological sort used?
Build systems, package managers (npm install order), task schedulers, spreadsheet recalculation and course planning.