Data Structures & Algorithms / Module 8: Graphs

Topic 8.5

Topological sort

The order to run dependent tasks, and how to detect circular dependencies.

9 min · intermediate

Watch: a task may only start once every task it's waiting for is done. The "waits" number drops each time a task finishes.

waits 0waits 1waits 1waits 1waits 2waits 2ordercodegeninstallbuildlintdeploytest
  • moving now
  • passed / marked
  • finished / the result
Step 1 of 8

An arrow from X to Y means Y needs X done first. 'waits n' = how many tasks must still finish before this one may run. Ready now: install.

Run anything that waits on nobody, then cross off its arrows. Repeat. If you get stuck before the end, there's a cycle.

Like getting dressed

Socks before shoes, trousers before shoes, shirt before jacket. There's no rule between socks and shirt, so either may come first. That's why a topological sort often has more than one correct answer. Only one thing matters: nothing goes on before whatever must be underneath it.

Code, for programmersKahn's algorithm
// deps: Map task -> tasks that must run after it (arrows out)
function topoSort(deps) {
  const waits = new Map();                         // task -> how many it still waits on
  for (const [task, next] of deps) {
    if (!waits.has(task)) waits.set(task, 0);
    for (const n of next) waits.set(n, (waits.get(n) ?? 0) + 1);
  }
  const ready = [...waits].filter(([, w]) => w === 0).map(([task]) => task);
  const order = [];
  while (ready.length) {
    const task = ready.shift();
    order.push(task);
    for (const n of deps.get(task) ?? []) {
      waits.set(n, waits.get(n) - 1);
      if (waits.get(n) === 0) ready.push(n);
    }
  }
  if (order.length < waits.size) throw new Error("circular dependency");
  return order;
}

Where you meet it

  • Build tools and monorepos: Turborepo and Nx build the packages that are needed first. Tasks that don't wait on each other can run in parallel.
  • Package managers: install dependencies before the packages that use them.
  • Database migrations: tables referenced by a foreign key are created first.
  • Spreadsheets: a cell is recalculated after every cell it refers to.
  • CI pipelines: needs: in GitHub Actions forms a graph like the one in the figure.

Quiz

  1. Which task may run first?

  2. Kahn's algorithm stops, but some tasks haven't run. What does it mean?

  3. Does a topological sort always have exactly one answer?

0 of 3 answered.