Skip to main content
Intermediate ~12 min read

Topological Sort

Order tasks that depend on each other: Kahn's queue algorithm, DFS post-order, and cycle detection on DAGs.

Prerequisites: Depth-First Search, Graph Representations

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

    Count in-degrees

    For every node, count incoming edges. Nodes with in-degree 0 depend on nothing, they are immediately schedulable.

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

topo-sort.js
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 / caseCostNotes
Kahn's algorithmO(V + E)each node and edge processed once
DFS reverse post-orderO(V + E)elegant alternative: finish times reversed give a valid order
Cycle detectionincludedorder 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.

Check your understanding

  1. 1.When does a directed graph have NO topological order?
  2. 2.In Kahn's algorithm, what does it mean when the queue empties but some nodes were never output?
  3. 3.A build system must compile 500 files with dependency rules. Which algorithm schedules the compilation order?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going