Topological sort
How to line up tasks so that everything a task depends on comes before it, shown on six courses with prerequisites: by counting arrows, and by depth-first search.
In 30 seconds
Some things must happen before others: a course before the one that builds on it, a library before the program that uses it. Draw each rule as an arrow and you get a graph.
A topological sort lists every item so that all arrows point forward. Kahn’s algorithm repeatedly takes an item with no unmet prerequisites; a depth-first search gets there by writing items down on the way back and reversing.
If the rules loop back on themselves, no such order exists, and the algorithm notices.
Topological sort, step by step
A graph usually has several valid orders; which one you get depends on which ready node is taken first. Real depth-first versions also mark nodes “in progress” to detect cycles.
- Step 1: Things that must wait. Six courses, and some need others first: ALGO needs both MATH and PROG, WEB needs ALGO and DATA. Each arrow means “before”. We want to put all six in one line so that no course comes before something it depends on. That line is a topological order.
- Step 2: Count incoming arrows. Give every course a counter: the number of arrows pointing at it, called its in-degree. It says how many prerequisites are still missing. MATH and PROG read 0, so nothing stops them: they are ready. This is the start of Kahn’s algorithm.
- Step 3: Take one, lower the rest. Move a ready course into the order and erase its outgoing arrows, lowering the counter of each course they pointed at. Taking MATH drops ALGO from 2 to 1. Taking PROG drops ALGO to 0 and DATA to 0, so those two become ready.
- Step 4: Repeat until empty. Keep taking ready courses: ALGO, DATA, then WEB, then PROJ. Laid out in a line, every arrow now points to the right, so every course comes after its prerequisites. Each course and each arrow was handled exactly once, so the time grows with nodes plus arrows.
- Step 5: The depth-first version. A second method: follow arrows as deep as possible and write a course down only when everything after it is written. Starting at MATH we reach PROJ first, so PROJ is written first; PROG is written last. Reverse that list and prerequisites come first. It is a different order, and just as valid.
- Step 6: A cycle has no order. Suppose someone adds a rule that ALGO needs PROJ. Now ALGO waits for PROJ, PROJ for WEB, and WEB for ALGO: a cycle. MATH, PROG and DATA come out, then no counter is 0 and the process stops with three courses left. Fewer courses placed than exist is exactly how Kahn’s algorithm detects a cycle.
- Step 7: Where it is used. Anything with “this before that” rules is a job for topological sort. Build tools compile a library before the program that uses it; package managers install dependencies first; spreadsheets recalculate a cell after the cells it reads. It works only on a directed graph with no cycles, a DAG.
Try it yourself
Learn this first
Learn next
- Dijkstra’s shortest pathGrow the cheapest frontier until you reach the goal. Intermediate
- Data pipelines and orchestrationA nightly report as a graph of tasks: scheduled, retried and backfilled. Beginner
- Adjacency list vs adjacency matrixTwo ways to store a graph, and what each costs in memory and lookups. Beginner
Spotted a mistake on this page?