Topological sort
A topological sort orders a directed graph's vertices so every edge points forward, like courses after their prerequisites; Kahn's algorithm keeps removing vertices with in-degree 0 using a queue, and if it gets stuck early, there is a cycle.
A computer science degree has prerequisites: data structures needs programming and discrete maths first, operating systems needs data structures and computer organization… Six courses need an order in which each comes after all of its prerequisites. A compiler deciding which file to build first, make deciding which target to make first, a spreadsheet deciding which cell to compute first: all the same problem, topological sort.
Prerequisites form a directed graph
Each course is a vertex, and "A is a prerequisite of B" is an edge A → B. The order we want has the start of every edge before its end.
Such an order exists exactly when the graph has no cycle: if A must come before B, B before C and C before A, nothing can go first. A directed graph without cycles is a directed acyclic graph (DAG).
Which course can go first? One with no prerequisites, that is, with in-degree 0. Once it's done, the edges out of it don't matter any more, so delete them; that leaves new courses with in-degree 0… This is Kahn's algorithm:
- Work out each vertex's in-degree and queue the ones with in-degree 0.
- While the queue isn't empty: take out u and output it; for each v that u points to, subtract 1 from v's in-degree, and queue v when it reaches 0.
queue
Which set of prerequisites can't be put in any order?
Directed edges B → A, B → D, C → A, A → E, D → E. Run Kahn's algorithm, queueing vertices in alphabetical order when several reach in-degree 0 together. What order comes out?
B C A D E is a valid topological order too, but a queue is first in, first out: D went in before A, so D comes out first.In C++: an in-degree table and a queue
This step writes Kahn's algorithm in C++. The graph is stored as an adjacency matrix: a[u][v] = 1 means there's an edge u → v, so the number of 1s in column v is v's in-degree. The queue is the STL's queue<int>: q.push(v) puts v in, q.front() looks at the one in front, q.pop() throws it away (it returns nothing), and q.empty() means nothing is left waiting. It's the six-course example again, numbered 0 to 5: C, DM, DS, CO, Alg, OS.
Each vertex goes in and out of the queue once, and each edge lowers an in-degree once: O(n + e) with an adjacency list, O(n²) with a matrix.
1#include <iostream>2#include <string>3#include <queue>4using namespace std;5 6const int N = 6;7 8string name[N] = {"Programming in C", "Discrete maths", "Data structures", "Computer organization", "Algorithms", "Operating systems"};9int a[N][N]; // a[u][v] = 1: u is a prerequisite of v10 11int topo(int order[]) { // returns how many were ordered12 int indeg[N] = {0}, k = 0;13 for (int u = 0; u < N; u++)14 for (int v = 0; v < N; v++)15 indeg[v] += a[u][v];16 queue<int> q;17 for (int v = 0; v < N; v++)18 if (indeg[v] == 0) q.push(v);19 while (!q.empty()) {20 int u = q.front();21 q.pop();22 order[k++] = u;23 for (int v = 0; v < N; v++)24 if (a[u][v] && --indeg[v] == 0) // delete u → v; queue v when its in-degree hits 025 q.push(v);26 }27 return k;28}29 30int main() {31 a[0][2] = a[1][2] = a[0][3] = 1;32 a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;33 int order[N];34 int k = topo(order);35 for (int i = 0; i < k; i++)36 cout << i + 1 << ". " << name[order[i]] << '\n';37 cout << (k == N ? "all ordered" : "a cycle: can't order them all") << '\n';38 return 0;39}
1. Programming in C 2. Discrete maths 3. Computer organization 4. Data structures 5. Algorithms 6. Operating systems all ordered
When the edge u → v is removed, v's in-degree has to go down by 1 first, and then you check whether it reached 0. What goes in the blank? The program should print 0 1 3 2 4 5.
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 6;6 7int a[N][N];8 9int main() {10 a[0][2] = a[1][2] = a[0][3] = 1;11 a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;12 int indeg[N] = {0};13 for (int u = 0; u < N; u++)14 for (int v = 0; v < N; v++)15 indeg[v] += a[u][v];16 queue<int> q;17 for (int v = 0; v < N; v++)18 if (indeg[v] == 0) q.push(v);19 while (!q.empty()) {20 int u = q.front();21 q.pop();22 cout << u << " ";23 for (int v = 0; v < N; v++)24 if (a[u][v]) {25 int& d = indeg[v]; // d is indeg[v] itself: a reference26 if ()27 q.push(v);28 }29 }30 cout << "\n";31 return 0;32}
--d subtracts first and compares the new value: the time the in-degree goes from 1 to 0 is exactly when v is queued. d-- compares the old value and subtracts afterwards, so at 1 it compares 1 and misses; d == 0 never subtracts at all. Both of those print only 0 1, and the later courses never get into the queue.A graph with n vertices and e edges is stored as an adjacency matrix, as in this level's program. How long does Kahn's algorithm take?
Write Kahn's algorithm
✓Fill in two places: first work out each vertex's in-degree from the adjacency matrix; then, in the while loop, take a vertex out, print it, subtract 1 from the in-degree of each vertex it points to, and queue any that reach 0.
0 5 1 2 6 3 4
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 7;6 7int a[N][N];8 9int main() {10 a[0][1] = a[0][2] = a[1][3] = a[2][3] = 1;11 a[3][4] = a[5][2] = a[5][6] = a[6][4] = 1;12 int indeg[N] = {0};13 // 1. indeg[v] = how many 1s are in column v14 queue<int> q;15 for (int v = 0; v < N; v++)16 if (indeg[v] == 0) q.push(v);17 while (!q.empty()) {18 int u = q.front();19 q.pop();20 // 2. print u; for each v: if a[u][v] is 1, indeg[v]--, and queue v when it reaches 021 }22 cout << '\n';23 return 0;24}
The earliest term for each course
✓You can take any number of courses in a term, but a course can only be taken the term after all its prerequisites are done. Courses with no prerequisites are in term 1. Work in topological order: when the edge u → v is deleted, sem[v] must be at least sem[u] + 1. Fill in that line and print each course's earliest term.
1 1 2 2 3 3
1#include <iostream>2#include <queue>3#include <algorithm>4using namespace std;5 6const int N = 6;7 8int a[N][N];9 10int main() {11 a[0][2] = a[1][2] = a[0][3] = 1;12 a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;13 int indeg[N] = {0}, sem[N];14 for (int u = 0; u < N; u++)15 for (int v = 0; v < N; v++)16 indeg[v] += a[u][v];17 queue<int> q;18 for (int v = 0; v < N; v++) {19 sem[v] = 1;20 if (indeg[v] == 0) q.push(v);21 }22 while (!q.empty()) {23 int u = q.front();24 q.pop();25 for (int v = 0; v < N; v++)26 if (a[u][v]) {27 // sem[v] becomes the larger of sem[v] and sem[u] + 128 if (--indeg[v] == 0) q.push(v);29 }30 }31 for (int v = 0; v < N; v++)32 cout << sem[v] << ' ';33 cout << '\n';34 return 0;35}
Topological orders aren't unique
At the start both C and DM have in-degree 0, and either can go first; later Alg and OS are in the same position. So a graph usually has more than one topological order: C DM DS CO OS Alg works, and so does DM C CO DS Alg OS, as long as every edge points from earlier to later. Swap the queue for a stack and it's still a correct topological sort, just giving another order:
The same graph with a stack instead of the queue: what does it print?
1#include <iostream>2#include <stack>3using namespace std;4 5const int N = 6;6 7int a[N][N];8 9int main() {10 a[0][2] = a[1][2] = a[0][3] = 1;11 a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;12 int indeg[N] = {0};13 for (int u = 0; u < N; u++)14 for (int v = 0; v < N; v++)15 indeg[v] += a[u][v];16 stack<int> st;17 for (int v = 0; v < N; v++)18 if (indeg[v] == 0) st.push(v);19 while (!st.empty()) {20 int u = st.top();21 st.pop();22 cout << u << ' ';23 for (int v = 0; v < N; v++)24 if (a[u][v] && --indeg[v] == 0)25 st.push(v);26 }27 cout << '\n';28 return 0;29}
There's also a DFS way: run DFS from each vertex, write a vertex down when all its successors are finished and it's about to return, and the reverse of that list is a topological order. The first to finish is a course with nothing after it, which belongs at the end anyway. The "With the STL" section writes it out.
The six-course graph: edges 0 → 2, 1 → 2, 0 → 3, 2 → 4, 1 → 4, 2 → 5, 3 → 5. Which one is not a topological order?
0 2 1 … puts 2 first. Check the other three edge by edge: every edge points forward.The same graph done with DFS: starting at 0, neighbours smallest first, the vertices finish (return) in the order 4 5 2 3 0 1. What topological order does that give?
1 0 3 2 5 4. Vertex 4 finished first because nothing comes after it, so it belongs last. 0 2 4 5 3 1 is the order DFS first reaches each vertex, and it's wrong: it gets the edge 1 → 2 backwards.Can't order them all: a cycle
Kahn's algorithm detects cycles for free: the vertices on a cycle wait for each other, their in-degrees never reach 0, and none of them ever gets into the queue. So the loop ends early with fewer than n output.
Get one prerequisite wrong: "algorithms is also a prerequisite of data structures". Now DS → Alg and Alg → DS, two courses waiting for each other: a cycle.
queue
Put the extra edge 4 → 2 into Kahn's program and run it:
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 6;6 7int a[N][N];8 9int topo(int order[]) {10 int indeg[N] = {0}, k = 0;11 for (int u = 0; u < N; u++)12 for (int v = 0; v < N; v++)13 indeg[v] += a[u][v];14 queue<int> q;15 for (int v = 0; v < N; v++)16 if (indeg[v] == 0) q.push(v);17 while (!q.empty()) {18 int u = q.front();19 q.pop();20 order[k++] = u;21 for (int v = 0; v < N; v++)22 if (a[u][v] && --indeg[v] == 0)23 q.push(v);24 }25 return k;26}27 28int main() {29 a[0][2] = a[1][2] = a[0][3] = 1;30 a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;31 a[4][2] = 1; // the extra 4 → 2: each a prerequisite of the other32 int order[N];33 int k = topo(order);34 cout << "ordered " << k << ": ";35 for (int i = 0; i < k; i++)36 cout << order[i] << ' ';37 cout << '\n' << (k == N ? "all ordered" : "a cycle: can't order them all") << '\n';38 return 0;39}
ordered 3: 0 1 3 a cycle: can't order them all
Forget the k == N check and the program cheerfully prints three courses, 0 1 3, looking as if it worked. A topological sort must always compare the count at the end.
Exam favourites: "write all topological orders of the graph": at each step try every vertex whose in-degree is 0, and draw it as a tree to count them. "If a directed graph's adjacency matrix is upper triangular (all 0 below the diagonal), it has a topological order": every edge goes from a lower number to a higher one, so 0 1 2 … n − 1 is one. And AOE networks and the critical path: along a topological order, work out each event's earliest time (take the maximum), then the latest times backwards; activities where the two are equal are on the critical path.
Directed edges 0 → 1, 1 → 2, 2 → 3, 3 → 1, 0 → 4. How many vertices does Kahn's algorithm get out?
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 5;6 7int a[N][N];8 9int main() {10 a[0][1] = a[1][2] = a[2][3] = a[3][1] = a[0][4] = 1;11 int indeg[N] = {0}, k = 0;12 for (int u = 0; u < N; u++)13 for (int v = 0; v < N; v++)14 indeg[v] += a[u][v];15 queue<int> q;16 for (int v = 0; v < N; v++)17 if (indeg[v] == 0) q.push(v);18 while (!q.empty()) {19 int u = q.front();20 q.pop();21 k++;22 for (int v = 0; v < N; v++)23 if (a[u][v] && --indeg[v] == 0)24 q.push(v);25 }26 cout << k << "\n";27 return 0;28}
A directed graph's adjacency matrix is upper triangular (the diagonal and everything below it are 0). What can you say about its topological orders?
a[u][v] = 1 only when u < v). Sorted by number, no edge points back, so there can't be a cycle. The order isn't necessarily unique, though: with no edges at all, any order works.With the STL
The everyday version: the adjacency list vector<vector<int>>, an in-degree table vector<int>, a queue<int> for Kahn, the result in a vector<int>, and at the end a check that its size() is n. The DFS way gives each vertex three states: 0 not visited, 1 still being recursed, 2 finished; reaching a vertex in state 1 means coming back to a path that isn't finished: a cycle. push_back on finishing, reverse at the end.
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8vector<int> kahn(const vector<vector<int>>& adj) {9 int n = adj.size();10 vector<int> indeg(n, 0), order;11 for (int u = 0; u < n; u++)12 for (int v : adj[u]) indeg[v]++;13 queue<int> q;14 for (int v = 0; v < n; v++)15 if (indeg[v] == 0) q.push(v);16 while (!q.empty()) {17 int u = q.front();18 q.pop();19 order.push_back(u);20 for (int v : adj[u])21 if (--indeg[v] == 0) q.push(v);22 }23 return order; // size() < n: a cycle24}25 26vector<int> dfsTopo(const vector<vector<int>>& adj, bool& cycle) {27 int n = adj.size();28 vector<int> state(n, 0), order; // 0 not visited, 1 being recursed, 2 finished29 cycle = false;30 function<void(int)> dfs = [&](int u) {31 state[u] = 1;32 for (int v : adj[u]) {33 if (state[v] == 1) cycle = true; // back to a vertex not finished yet34 else if (state[v] == 0) dfs(v);35 }36 state[u] = 2;37 order.push_back(u); // all successors done: now write it down38 };39 for (int u = 0; u < n; u++)40 if (state[u] == 0) dfs(u);41 reverse(order.begin(), order.end());42 return order;43}44 45void show(const char* title, const vector<int>& v) {46 cout << title;47 for (int x : v) cout << x << ' ';48 cout << '\n';49}50 51int main() {52 int n = 6;53 int edges[7][2] = {{0, 2}, {1, 2}, {0, 3}, {2, 4}, {1, 4}, {2, 5}, {3, 5}};54 vector<vector<int>> adj(n);55 for (auto& e : edges) adj[e[0]].push_back(e[1]); // directed edge: one end only56 57 bool cycle;58 show("Kahn: ", kahn(adj));59 show("DFS: ", dfsTopo(adj, cycle));60 cout << (cycle ? "cycle" : "no cycle") << '\n';61 62 adj[4].push_back(2); // the extra 4 → 263 cout << "with 4 → 2, Kahn orders " << kahn(adj).size() << "; ";64 dfsTopo(adj, cycle);65 cout << "DFS: " << (cycle ? "cycle" : "no cycle") << '\n';66 return 0;67}
Kahn: 0 1 3 2 4 5 DFS: 1 0 3 2 5 4 no cycle with 4 → 2, Kahn orders 3; DFS: cycle
DFS from 0 finishes in the order 4 5 2 3 0 1 (4 and 5 have nothing after them, so they finish first); reversed, 1 0 3 2 5 4: the same answer the stack version gave, and a valid topological order.
When a problem says "if there are several answers, print the smallest", swap the queue<int> for a min-heap priority_queue<int, vector<int>, greater<int>>: each time it hands out the lowest-numbered vertex with in-degree 0.
| Method | Uses | Cycle check | Cost |
|---|---|---|---|
| Kahn | vector<int> indeg + queue<int> | fewer than n ordered | O(n + e) |
| Kahn, smallest order | priority_queue<int, vector<int>, greater<int>> | same | O((n + e) log n) |
| DFS | recursion + state 0/1/2, then reverse | reaching a vertex in state 1 | O(n + e) |
In interviews: "course schedule" (can you take every course, and in what order), "task dependencies", "build order" are all topological sort, and Kahn is the safest: no recursion, and the cycle check is just comparing order.size() with n. The edges are often given as [course, prerequisite], the opposite way to "prerequisite → course", so decide which way the edges point before you build the graph.
The problem says: when there are several topological orders, output the lexicographically smallest (take the smallest number at every step). What should Kahn's queue<int> become?
priority_queue<int> is a max-heap by default and would give you the largest; a stack is last in, first out. A queue only goes by arrival: in the six-course graph 3 is queued before 2, so 3 comes out first.Summary
Topological sort: keep taking in-degree 0
- Only a directed acyclic graph has a topological order, usually more than one
- Kahn: queue in-degree 0; take one out, lower the in-degrees it points to, queue any at 0
- Fewer than n ordered means a cycle: always compare the count at the end
- O(n + e); the DFS way reverses the finishing order, and a vertex still being recursed means a cycle
1while (!q.empty()) {2 int u = q.front(); q.pop();3 order.push_back(u);4 for (int v : adj[u])5 if (--indeg[v] == 0) q.push(v);6}