AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Topological Sort

Line up a DAG so every arrow points forward — repeatedly output a node with no remaining prerequisites (Kahn's algorithm).

8 min read Watch it move Build it

A topological sort lines up the vertices of a directed acyclic graph (DAG) so that every arrow points forward — if there's an edge A → B, then A appears before B. It's the answer to any 'what order can I do these in?' question where some tasks must precede others: course prerequisites, build dependencies, spreadsheet recalculation.

Only works on a DAG
A valid ordering exists only when there are no cycles. A cycle A → B → A would demand that A come before B *and* B before A — impossible. So a topological sort either succeeds or proves the graph has a cycle.

Kahn's algorithm — peel off the ready nodes

The key number is each vertex's in-degree: how many arrows point *into* it — its count of unmet prerequisites. A vertex with in-degree 0 has nothing blocking it, so it's safe to output now. Output it, remove its outgoing edges (which lowers its neighbours' in-degrees), and that may free up new zero-in-degree vertices.

  1. 1Compute the in-degree of every vertex.
  2. 2Put all in-degree-0 vertices into a queue — they have no prerequisites.
  3. 3Dequeue a vertex, append it to the output order.
  4. 4For each of its out-neighbours, decrement their in-degree; if one hits 0, enqueue it.
  5. 5Repeat until the queue empties.
function kahn(V, adj) {
  const indeg = Array(V).fill(0);
  for (let u = 0; u < V; u++) for (const v of adj[u]) indeg[v]++;
  const queue = [];
  for (let u = 0; u < V; u++) if (indeg[u] === 0) queue.push(u);
  const order = [];
  while (queue.length) {
    const u = queue.shift();
    order.push(u);
    for (const v of adj[u]) if (--indeg[v] === 0) queue.push(v);
  }
  return order.length === V ? order : null; // null => a cycle exists
}
A built-in cycle detector
If the output ends up shorter than V, some vertices never reached in-degree 0 — they're tangled in a cycle that never releases them. So Kahn's algorithm tells you *for free* whether the graph was acyclic at all.
OperationTimeSpace
Kahn's algorithm · each vertex and edge processed onceO(V + E)O(V)
Check yourself
In Kahn's algorithm, which vertices are ready to be output at any moment?