Graph Algorithm

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, react

Kahn's BFS — animated

topoSort DAG: A→B, A→C, B→D, C→Dstep 1/5

// Array state

A:0
Q
B:1
[1]
C:1
[2]
D:2
[3]
→ in-degrees: A=0, B=1(A), C=1(A), D=2(B,C). Queue:[A]

// Pseudocode

1// Kahn's algorithm — BFS topological sort
2function 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)

Algorithm walkthrough

1 / 4
1

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.

1 of 4

Kahn's algorithm

kahn-topo.pseudo
1// Kahn's algorithm — BFS topological sort
2function 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

dfs-topo.pseudo
1// DFS post-order topological sort
2function 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()
9 
10function 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

Time — O(V+E): visit every vertex and edge onceO(n)

Linear time

Space — in-degree array + queue/stackO(n)

Linear time

⚠️Only valid on DAGs
Topological sort requires a Directed Acyclic Graph. If the graph has a cycle, no valid ordering exists. Kahn's algorithm detects cycles automatically: if result.length < V, a cycle exists.

🎯 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.