Topological sorting
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Topological sorting puts tasks that depend on each other into an order where every task comes after the things it needs. If no such order exists, it means there is a circular dependency, which it detects as a bonus.
Practical use cases
- Web app: Installing packages in the right order. A package manager like npm or Composer must install a library only after the libraries it needs. Treating dependencies as arrows and repeatedly installing whatever has nothing left to wait for produces a safe order. The install finishes without "missing dependency" errors, and circular packages are reported at once.
- Web app: Course prerequisites in a college portal. A student portal builds a study plan from courses with prerequisites. Ordering them so every prerequisite comes first gives the semester plan, and a loop in the rules is reported as an error. Students see a clear order of courses, and registrars get a warning about impossible prerequisite loops.
- Web app: Laravel job pipelines and database migrations. A deployment runs migrations or jobs where some need others to finish first. Sorting them by dependency tells the system what to run first and what can run in parallel. Independent tasks can run side by side, so a deployment finishes sooner and never runs a step too early.
- System: Build systems and spreadsheets. Build tools compile files after the files they use, and a spreadsheet recalculates cells in an order where each formula's inputs are ready first. Edit a cell and everything that depends on it updates in the right order, with no stale values.
The story: The Course Schedule Knot
Mrs. Sharma’s college-prep class had five courses with rules like "Algebra before Geometry", "Geometry before Trigonometry". Aarav stared at the list: "In what order should I study so I never start a course whose prerequisite I haven’t done?"
He drew each course as a dot and each rule as an arrow. Then Mira whispered: "Who can I start today? Whoever has no arrow pointing into them." Only Algebra. So he did it, and crossed it out, which also erased every arrow leaving Algebra. Suddenly Geometry and Statistics had no arrows left on them. Their turn.
Repeat: pick anything with no arrows pointing in, do it, erase its outgoing arrows. By the end every course appeared in a valid order. And if at some point everyone left still has an arrow pointing in, like "A needs B" and "B needs A", then you have a circle of demands and the plan is impossible.
This is topological sorting (Kahn’s method). The smell: "prerequisites", "dependencies", "build order", "before / after", "can all tasks be finished?", any directed relationship where order matters, and cycle detection as a bonus.
How to spot this problem, and where you need it
You have tasks, items or steps with "A must come before B" rules, and you need a valid order, or to find out that the rules contradict each other.
Signs you need it
- The data is a list of prerequisites or dependencies, such as "task B needs task A".
- The problem says "order of tasks", "build order", "course schedule" or "can all be completed".
- Doing things in the wrong order causes errors like a missing table or a function that does not exist yet.
Where to use it in a project
- Package install, build and deploy pipelines where steps depend on earlier steps.
- Course, project and workflow planners where some tasks need others to finish first.
- Spreadsheet or formula engines that must update dependent cells in a safe order.
The solution
Count, for each task, how many tasks it still waits for. Put every task with zero waits in a queue. Take one from the queue, add it to the output order, and reduce the wait count of each task that depended on it, queuing any that reach zero. Repeat. If the output has fewer tasks than the input, there is a circular dependency, which you report.
Payoff: Before: errors from running steps in the wrong order, and endless waiting on loops. After: a correct order in one pass, with loops reported clearly.
Explain it like I am 8
To get dressed, socks go on before shoes, and underwear before trousers. Draw arrows for "must happen first". Start with whatever has no arrow pointing at it, do it, rub out its arrows, and repeat. If you ever get stuck with everything blocked, the rules argue with each other.
How it works, step by step
- Spot the clue: tasks with "must come before" rules, a build/install order, or "can I finish all courses?".
- Build the graph: an arrow
a → bfor each "a before b", and count each node's in-degree (arrows pointing in). - Queue every node with in-degree 0. These are free to start.
- Pop one, add it to the order, and reduce the in-degree of each node it points to. If one drops to 0, queue it.
- Finish: if the order holds all n nodes, return it. If fewer, a cycle blocked some nodes: no valid order exists.
The code in four languages
PHP
<?php
// Classic: "Course Schedule II": a valid order, or [] if a cycle blocks it.
function courseOrder(int $n, array $rules): array { // each rule: [before, after]
$next = array_fill(0, $n, []); // who comes after whom
$inDegree = array_fill(0, $n, 0); // unfinished prerequisites
foreach ($rules as [$before, $after]) {
$next[$before][] = $after;
$inDegree[$after]++;
}
$queue = [];
for ($i = 0; $i < $n; $i++) {
if ($inDegree[$i] === 0) $queue[] = $i; // free to start now
}
$order = [];
for ($head = 0; $head < count($queue); $head++) {
$u = $queue[$head];
$order[] = $u;
foreach ($next[$u] as $v) {
$inDegree[$v]--; // one prerequisite finished
if ($inDegree[$v] === 0) $queue[] = $v; // all prerequisites done
}
}
return count($order) === $n ? $order : []; // fewer than n means a cycle
}
echo json_encode(courseOrder(5, [[0,1],[0,2],[1,3],[2,3],[3,4]])), "
"; // [0,1,2,3,4]
echo json_encode(courseOrder(2, [[0,1],[1,0]])), "
"; // [] (cycle)JavaScript
// Classic: "Course Schedule II": a valid order, or [] if a cycle blocks it.
function courseOrder(n, rules) { // each rule: [before, after]
const next = Array.from({ length: n }, () => []); // who comes after whom
const inDegree = new Array(n).fill(0); // unfinished prerequisites
for (const [before, after] of rules) {
next[before].push(after);
inDegree[after]++;
}
const queue = [];
for (let i = 0; i < n; i++) {
if (inDegree[i] === 0) queue.push(i); // free to start now
}
const order = [];
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
order.push(u);
for (const v of next[u]) {
inDegree[v]--; // one prerequisite finished
if (inDegree[v] === 0) queue.push(v); // all prerequisites done
}
}
return order.length === n ? order : []; // fewer than n means a cycle
}
console.log(JSON.stringify(courseOrder(5, [[0,1],[0,2],[1,3],[2,3],[3,4]]))); // [0,1,2,3,4]
console.log(JSON.stringify(courseOrder(2, [[0,1],[1,0]]))); // [] (cycle)Java
import java.util.*;
public class Main {
// Classic: "Course Schedule II": a valid order, or [] if a cycle blocks it.
static List<Integer> courseOrder(int n, int[][] rules) { // each rule: {before, after}
List<List<Integer>> next = new ArrayList<>(); // who comes after whom
for (int i = 0; i < n; i++) next.add(new ArrayList<>());
int[] inDegree = new int[n]; // unfinished prerequisites
for (int[] rule : rules) {
next.get(rule[0]).add(rule[1]);
inDegree[rule[1]]++;
}
List<Integer> queue = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) queue.add(i); // free to start now
}
List<Integer> order = new ArrayList<>();
for (int head = 0; head < queue.size(); head++) {
int u = queue.get(head);
order.add(u);
for (int v : next.get(u)) {
inDegree[v]--; // one prerequisite finished
if (inDegree[v] == 0) queue.add(v); // all prerequisites done
}
}
return order.size() == n ? order : List.of(); // fewer than n means a cycle
}
public static void main(String[] args) {
System.out.println(courseOrder(5, new int[][]{{0,1},{0,2},{1,3},{2,3},{3,4}})); // [0, 1, 2, 3, 4]
System.out.println(courseOrder(2, new int[][]{{0,1},{1,0}})); // [] (cycle)
}
}Go
package main
import "fmt"
// courseOrder is "Course Schedule II": a valid order, or an empty slice if a cycle blocks it.
func courseOrder(n int, rules [][2]int) []int { // each rule: {before, after}
next := make([][]int, n) // who comes after whom
inDegree := make([]int, n) // unfinished prerequisites
for _, rule := range rules {
before, after := rule[0], rule[1]
next[before] = append(next[before], after)
inDegree[after]++
}
var queue []int
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i) // free to start now
}
}
order := []int{}
for head := 0; head < len(queue); head++ {
u := queue[head]
order = append(order, u)
for _, v := range next[u] {
inDegree[v]-- // one prerequisite finished
if inDegree[v] == 0 {
queue = append(queue, v) // all prerequisites done
}
}
}
if len(order) != n {
return []int{} // fewer than n means a cycle
}
return order
}
func main() {
fmt.Println(courseOrder(5, [][2]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}})) // [0 1 2 3 4]
fmt.Println(courseOrder(2, [][2]int{{0, 1}, {1, 0}})) // [] (cycle)
}Time: O(V + E) · Extra space: O(V + E). Each course and each rule is handled once.
Watch out for
- Reversing the arrow direction, so you get the order backwards (or the wrong in-degrees).
- Not checking that every node was output. If you return a partial order you miss the cycle.
- Expecting one unique answer: there are often several valid orders (B before C or C before B here).
Quick check
- Which clue says "topological sort"?
- "shortest path with weights"
- "count islands"
- "all subsets"
- "tasks with prerequisites; find a valid order"
- What does it mean if the output has fewer nodes than the graph?
- The graph is a tree
- Some nodes were extra
- The graph has a cycle
- The algorithm is faster
- Which nodes start in the queue?
- Those with in-degree 0
- Those with the most arrows leaving
- Those with the most arrows entering
- The last node