← Knowledgebase

Topological sort: Kahn's algorithm

The problem

Many things come with "this before that" rules: courses and their prerequisites, build steps, spreadsheet cells that depend on other cells. Draw each rule as an arrow X → Y ("X must come before Y") and you get a directed graph. A topological order lists every node so that all arrows point forward.

That's only possible if the graph has no cycle: if A must precede B, B precede C, and C precede A, nothing can go first. A directed graph without cycles is called a DAG (directed acyclic graph).

Kahn's algorithm

  1. Count each node's in-degree: how many arrows point into it.
  2. A node with in-degree 0 has nothing left to wait for: it's ready. Place a ready node next.
  3. Remove its outgoing arrows, lowering each target's in-degree by one. Any that reach 0 become ready.
  4. Repeat until every node is placed.

If at some point nodes remain but none is ready, they are all waiting on each other: the graph has a cycle, and no topological order exists. So Kahn's algorithm also detects cycles.

Reading the pictures

Under each node not yet placed is its current in-degree (in=…). Placed nodes are filled, and the arrows they used up fade. When several nodes are ready at once, any of them is a valid choice; these pages always take the alphabetically first, so each question has one answer.

Kahn's algorithm
TimeO(V + E): each node is placed once and each arrow removed once.
AlternativeRun DFS and list nodes in reverse order of when they finish.