Topological sort
Order the vertices of a directed acyclic graph so every edge points forward: the order to run tasks, build packages or apply migrations so dependencies come first.
Description
Given tasks with dependencies, in what order can you do them so that nothing starts before its prerequisites? Model the tasks as a directed graph where an edge from A to B means "A must come before B". A topological order lists every vertex so that all edges point forward.
Such an order exists exactly when the graph has no cycles, a DAG. If A depends on B, B on C and C on A, no valid order exists, and a good algorithm reports the cycle instead.
Kahn's algorithm, shown in the step-through, counts each vertex's incoming edges (its unmet prerequisites). Vertices with none are ready; put them in a queue. Repeatedly take a ready vertex, output it, and remove its outgoing edges; any vertex whose count drops to zero becomes ready. If vertices remain when the queue is empty, they're part of a cycle.
The alternative is DFS-based: run depth-first search and output vertices in reverse finishing order. Both are O(V + E). Topological sorting is behind build systems (make, Bazel), package managers, spreadsheet recalculation, database migrations and CI pipelines.
How it works
Tasks and their dependencies: an arrow means "must come before"
- design → schema
- design → ui
- schema → api
- api → tests
- ui → tests
- tests → deploy
Step through: Kahn's algorithm. Numbers show remaining prerequisites.
Ready queue designOutput none yet
Step 1 of 14Count incoming edges for each vertex. design has none, so it can go first.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Kahn's algorithm | O(V + E) | O(V + E) |
| DFS-based | O(V + E) | O(V + E) |
| Detect a cycleComes free with either algorithm. | O(V + E) | O(V + E) |
Space: O(V) for the counts and the queue
A DAG often has many valid orders. Kahn's algorithm with a priority queue instead of a plain queue gives a deterministic, for example alphabetical, order.
TypeScript implementation
Kahn's algorithm, returning a valid order or the vertices stuck in a cycle.
// Kahn's algorithm: repeatedly output a vertex with no remaining prerequisites.
type Dependencies = Record<string, string[]>; // task → tasks that must come after it
export function topoSort(g: Dependencies): { order: string[]; cycle: string[] } {
const indegree = new Map<string, number>();
for (const v of Object.keys(g)) indegree.set(v, indegree.get(v) ?? 0);
for (const targets of Object.values(g)) for (const t of targets) indegree.set(t, (indegree.get(t) ?? 0) + 1);
const ready = [...indegree].filter(([, d]) => d === 0).map(([v]) => v).sort();
const order: string[] = [];
while (ready.length) {
const v = ready.shift()!;
order.push(v);
for (const t of g[v] ?? []) {
const d = indegree.get(t)! - 1;
indegree.set(t, d);
if (d === 0) {
ready.push(t);
ready.sort(); // deterministic, alphabetical among ready tasks
}
}
}
// anything not output still has prerequisites: it's on or behind a cycle
const cycle = [...indegree].filter(([v]) => !order.includes(v)).map(([v]) => v);
return { order, cycle };
}
export function demo(): string[] {
const project: Dependencies = {
design: ["schema", "ui"],
schema: ["api"],
api: ["tests"],
ui: ["tests"],
tests: ["deploy"],
deploy: [],
};
const ok = topoSort(project);
const broken = topoSort({ ...project, deploy: ["design"] });
return [
`build order: ${ok.order.join(" → ")}`,
`with deploy → design added: ${broken.order.length ? broken.order.join(", ") : "nothing can start"}; stuck in a cycle: ${broken.cycle.join(", ")}`,
];
}When to use it
Use it when
- Ordering work with dependencies: builds, deployments, migrations, course prerequisites, task schedulers.
- Detecting circular dependencies and reporting them.
- As a step in other algorithms on DAGs, such as longest-path and critical-path scheduling.
Avoid it when
- The graph can legitimately have cycles: find strongly connected components first.
- You need to schedule with durations and limited resources: topological order is only the starting point.
Pitfalls
- Edge direction confusion: decide whether A → B means "A before B" or "A depends on B", and stick to it.
- Ignoring cycles, which leaves some vertices silently out of the result.
- Assuming the order is unique: tests that compare to one exact order may break when the input order changes.
Alternatives
DFS-based ordering
Choose it when you're already running DFS, or want reverse post-order directly.
Critical path method
Choose it when tasks have durations and you need the earliest finish time.