Topological Sort — Algorithms

Topological sort orders things so each one comes after all its dependencies (the things it needs), for example packages (ready-made code) in npm. Kahn's…

In the morning you get ready to go out: socks before shoes, shirt before tie. Trousers and socks can go in either order. Without thinking about it, you make an order that breaks none of the "this before that" rules.

Topological sort puts a list of things in order with the same rule: each thing comes after everything it needs. An example is a package manager such as npm, a program that installs packages (ready-made code written by other people). react-dom needs react, so react has to be installed first. A package that another one needs is called a dependency: react is a dependency of react-dom.

Kahn: install what isn't waiting for anything

There are five packages. Their rules are written as pairs [what is needed, what needs it]: react before react-dom, react before next, react-dom before next, tailwind before app, next before app.

Each package has an in-degree: how many dependencies it is still waiting for. At the start react has 0, react-dom 1, next 2, tailwind 0, app 2. A package with an in-degree of 0 can be installed right away, so it goes into the queue. At each step, the package at the front of the queue is installed, and the in-degree of every package waiting for it drops by one:

Step Installed In-degrees that drop Queue after
1 react react-dom becomes 0, next becomes 1 tailwind, react-dom
2 tailwind app becomes 1 react-dom
3 react-dom next becomes 0 next
4 next app becomes 0 app
5 app none empty

The order: react, tailwind, react-dom, next, app. This way of doing it is called Kahn's algorithm.

Here is Kahn's algorithm in JavaScript. deps holds the five rules above:

const deps = [
  ["react", "react-dom"],
  ["react", "next"],
  ["react-dom", "next"],
  ["tailwind", "app"],
  ["next", "app"],
];

function topoSort(nodes, deps) {
  const inDegree = {};
  const dependents = {};
  for (const n of nodes) {
    inDegree[n] = 0;
    dependents[n] = [];
  }
  for (const [before, after] of deps) {
    dependents[before].push(after);
    inDegree[after]++;
  }

  const queue = nodes.filter((n) => inDegree[n] === 0);
  const order = [];
  while (queue.length > 0) {
    const node = queue.shift();
    order.push(node);
    for (const m of dependents[node]) {
      inDegree[m]--;
      if (inDegree[m] === 0) queue.push(m);
    }
  }

  return order.length === nodes.length ? order : null;
}

console.log(topoSort(["react", "react-dom", "next", "tailwind", "app"], deps));
// ["react", "tailwind", "react-dom", "next", "app"]

A small example: C needs A and B, B needs A. The in-degrees are A 0, B 1, C 2. Install A, then B, then C. Each package and each dependency is handled only once. So twice the data takes roughly twice the time.

When there's a cycle

Now try this: a needs b, b needs c, and c needs a. Which one gets installed first? None. The three wait for each other in a circle, which is called a cycle. None has an in-degree of 0, so the queue is empty from the start. There's no right order, and topoSort returns null.

That's why topological sort only works on a DAG (directed acyclic graph): a graph whose edges have a direction and that has no cycle. In this example, each package is a node, and each pair is an edge whose direction goes from what is needed to what needs it.

Another option is topological sort with DFS from the BFS & DFS lesson. In this code, visit(node) first visits every package that waits for node. node is added to order only after all of them, so order is backwards, and reverse() turns it around at the end:

function topoSortDFS(nodes, deps) {
  const dependents = {};
  for (const n of nodes) dependents[n] = [];
  for (const [before, after] of deps) dependents[before].push(after);
  const state = {}; // 1: being visited, 2: finished
  const order = [];
  function visit(node) {
    if (state[node] === 1) return false; // a cycle
    if (state[node] === 2) return true;
    state[node] = 1;
    for (const m of dependents[node]) if (!visit(m)) return false;
    state[node] = 2;
    order.push(node);
    return true;
  }
  for (const n of nodes) if (!visit(n)) return null;
  return order.reverse();
}
console.log(topoSortDFS(["react", "react-dom", "next", "tailwind", "app"], deps));
// ["tailwind", "react", "react-dom", "next", "app"]

This order differs from Kahn's result, but it is also right: every package still comes after its dependencies. When DFS meets a package again that is still being visited (state 1), the path goes in a circle: that is a cycle, and the result is null. Kahn's steps are easier to follow, and its queue shows the packages that can be installed at the same time. DFS is handy when you already have DFS code.

⚠️ Reversed pairs, missed cycles, and more than one right order

TL;DR: Topological sort orders things so each one comes after all its dependencies (the things it needs), for example packages (ready-made code) in npm. Kahn's algorithm: count each package's in-degree (how many dependencies it still waits for), then put the ones at 0 in a queue (first in, first out). Install packages one by one from the front of the queue, lower the in-degree of every package waiting for them, and queue whatever reaches 0. If something never gets installed, there's a cycle (packages waiting for each other): return null. Topological sort only works on a DAG, a directed graph with no cycle. C needs A and B, B needs A: the order is A, B, C.

⚡ In-degree: how much is still awaited

Meaning: Topological sort orders packages (ready-made code written by other people) so each one is installed after all its dependencies (the packages it needs). The in-degree is how many dependencies a package is still waiting for. A package with an in-degree of 0 can be installed right away, so it goes into the queue.

⚡ Kahn's algorithm

Write:

function topoSort(nodes, deps) {
  const inDegree = {};
  const dependents = {};
  for (const n of nodes) {
    inDegree[n] = 0;
    dependents[n] = [];
  }
  for (const [before, after] of deps) {
    dependents[before].push(after);
    inDegree[after]++;
  }

  const queue = nodes.filter((n) => inDegree[n] === 0);
  const order = [];
  while (queue.length > 0) {
    const node = queue.shift();
    order.push(node);
    for (const m of dependents[node]) {
      inDegree[m]--;
      if (inDegree[m] === 0) queue.push(m);
    }
  }

  return order.length === nodes.length ? order : null;
}

Meaning: nodes is the list of all packages. deps holds pairs [before, after]: after needs before, so what is needed comes first. inDegree stores each package's in-degree, and dependents lists the packages waiting for each one. Each time the while loop repeats, the package at the front of the queue is installed (added to order). Every package waiting for it drops its in-degree by one, and whatever reaches 0 joins the queue. If order doesn't hold every package, the result is null.

⚡ When there's a cycle

Guess first: a needs b, b needs c, and c needs a. Which one gets installed first?

None. They all wait for each other, so none has an in-degree of 0. The queue is empty from the start, and the result is null.

Meaning: Packages that wait for each other in a circle form a cycle. Topological sort only works on a DAG: a directed graph with no cycle. Here each package is a node, and each pair [before, after] is an edge. There can also be more than one right order.

What you will learn