Data Structures & Algorithms / Module 8: Graphs
Topic 8.5
Topological sort
The order to run dependent tasks, and how to detect circular dependencies.
Watch: a task may only start once every task it's waiting for is done. The "waits" number drops each time a task finishes.
- moving now
- passed / marked
- finished / the result
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
Which task may run first?
Kahn's algorithm stops, but some tasks haven't run. What does it mean?
Does a topological sort always have exactly one answer?
0 of 3 answered.