Order tasks after their dependencies, and detect the cycle that makes an order impossible.
You build an app, and a build tool runs its steps. Some steps need others to finish first. You cannot bundle the code before it is compiled, and you cannot publish before the tests pass.
Here are the steps. Each line says before after: the first step must finish before the second can start.
0 1 install the packages, then compile the code
0 2 install the packages, then compile the styles
1 3 compile the code, then bundle
2 3 compile the styles, then bundle
1 4 compile the code, then run the tests
3 5 bundle, then publish
4 5 run the tests, then publishThe steps are numbered 0 to 5. The build tool needs one list that runs every step exactly once, with each step after everything it needs. For example, 0, 1, 2, 4, 3, 5 works. So does 0, 2, 1, 3, 4, 5.
The picture is a dependency graph: a vertex for each step and an arrow for each "before" rule. This graph has no loop, so it is a DAG, a directed acyclic graph. A topological sort puts the vertices of a DAG in a line so that every arrow points forward.
You met the graph as lists of arrows in Graphs (S6), and a queue in Queues (S3). The search from BFS and DFS on a grid (A1) comes back in the second method.
You get dressed. Socks come before shoes, trousers come before the belt, and a shirt comes before a jacket. Some things do not care about each other: you can put on a watch at any time.
You look for something you can do right now, with nothing left to wait for. You do it, and then some other item has nothing left to wait for. You repeat until you are dressed.
Kahn's algorithm works the same way. A queue holds the things that are ready.
Kahn's algorithm works like getting dressed: do whatever has nothing left to wait for, then see what becomes ready.
The second method has its own picture. Start from a task and follow what it unlocks, as deep as you can: install, then compile, then bundle, then publish. Publish unlocks nothing, so it goes on your list first. Then back up, and write each task down only when everything it unlocks is already on the list.
When you read the list from the end to the start, every task comes after the things it needs.
The DFS method works the same way: go deep first, write a step down when it finishes, then reverse the list.
Predict what happens
Q On the build map, you compile the code (1) and the styles (2) after installing (0). Which steps can you do next, once 0 is done?
Answer: B
After step 0, steps 1 and 2 only waited for step 0. Both are ready, so either can go first. Step 3 still waits for both.
Kahn's algorithm keeps three things.
Each round does two things.
The player below runs Kahn's algorithm. The table beside the map shows each in-degree, and the queue and the order are listed under it. Press Next to step, or Play. At some steps the player stops and asks you to predict.
Kahn's algorithm takes a step from the queue, adds it to the order and removes its arrows; a step that reaches in degree zero joins the queue.
Step by step: Kahn on the build steps. The animated player loads in your browser.
Look at the finished order: 0, 1, 2, 4, 3, 5. Steps 1 and 2 were both ready after step 0, and 1 was taken first because it joined the queue first. Step 3 waited for both 1 and 2, so its in-degree only reached 0 after both were gone.
Exercise · Put it in order: Kahn's loop. Arrange the lines into Kahn's algorithm. The list holds the ready steps and is also the order: reading it by position takes steps from the front. It returns the order, or an empty list when a cycle is left.
def kahn(after, indeg):
queue = [v for v in range(len(after)) if indeg[v] == 0]
for v in queue:
for u in after[v]:
indeg[u] -= 1
if indeg[u] == 0:
queue.append(u)
return queue if len(queue) == len(after) else []
indeg[u] += 1Predict what happens
Q The queue holds step 2. Step 1 was taken, and removing its arrow gives step 4 an in-degree of 0. Where does step 4 go?
Answer: B
A queue is first in, first out. Step 4 joins at the back, behind step 2, so step 2 is taken first.
Now picture a build where compiling the code needs the bundle, and bundling needs the compiled code. Each waits for the other.
Step by step: Kahn on a build that loops. The animated player loads in your browser.
The queue ran empty with only one step in the order. The steps left, 1, 2 and 3, each wait for another one of them, so none can start. That is a cycle, and no order exists. The tool reports an error.
When the rules loop, the queue runs dry before every step is placed: the steps left over wait on each other.
Exercise · Predict the output: How many steps get placed?. Five build steps with the rules 0 before 1, 1 before 2, 2 before 1, 2 before 3 and 3 before 4. Kahn's algorithm runs until its queue is empty and prints how many steps it placed. What does it print?
from collections import deque
n, edges = 5, [[0, 1], [1, 2], [2, 1], [2, 3], [3, 4]]
after = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges:
after[a].append(b)
indeg[b] += 1
queue = deque(v for v in range(n) if indeg[v] == 0)
order = []
while queue:
v = queue.popleft()
order.append(v)
for u in after[v]:
indeg[u] -= 1
if indeg[u] == 0:
queue.append(u)
print(len(order))There is a second way. Walk the graph depth first, from BFS and DFS on a grid (A1). Visit a step's followers before you finish the step. When none are left, the step is finished, and you write it in a list, then reverse the list at the end.
On the build map, the finish order is 5, 3, 4, 1, 2, 0. Reversed, it is 0, 2, 1, 4, 3, 5, and every arrow points forward in it. Step 5 finished first, because nothing comes after it. Step 0 finished last, because everything depends on it.
Keep a mark on each vertex: not started, in progress, or finished. If the walk reaches a vertex that is in progress, it has come back to a step it is still inside of. That is a cycle.
The depth first method writes a step down when it finishes, which is after everything that follows it; reversed, that list is a valid order.
Exercise · Break it: The order for a build that loops. This DFS method only remembers which steps it has seen, and it returns the reversed finish order. It should return an empty list when the rules contain a cycle. Find a map where it returns an order instead.
def topo_dfs(n, edges):
after = [[] for _ in range(n)]
for a, b in edges:
after[a].append(b)
seen = [False] * n
finished = []
def visit(v):
seen[v] = True
for u in after[v]:
if not seen[u]:
visit(u)
finished.append(v)
for v in range(n):
if not seen[v]:
visit(v)
return finished[::-1]Pick a map and run Kahn's algorithm. Step through forwards and back.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
A vertex with in-degree 0 has no arrow pointing at it. It waits for nothing. Put it first in the line, and every arrow that leaves it points forward, which is the right way.
Now take that vertex out, together with its arrows. What is left is a smaller graph. The same rule applies to it: some vertex has in-degree 0, unless a loop is left. Repeat until nothing is left.
A vertex with in-degree 0 waits for nothing, so it can safely come next. Taking it out lowers its neighbours' in-degrees and leaves a smaller problem of the same kind.
Why does a cycle stop it? Look at any cycle. Every vertex on it has an arrow coming from another vertex of the same cycle, so its in-degree never reaches 0. None of them can go first, the queue runs dry, and some vertices are never placed.
So the test is: count the vertices in the order. Fewer than n means a cycle.
Take any arrow from a to b. We want a to come before b in the final order, so a must finish after b.
If the walk reaches a first, it goes on to b (or already finished b), so b finishes before a. If the walk reaches b first, it finishes b without ever coming back to a, because a is not reachable from b in a graph with no cycle. So b finishes before a either way.
The rule to remember: a step finishes only after every step that depends on it has finished. So reversing the finish order puts every step before the steps that depend on it. A step reached again while still in progress closes a cycle.
Predict what happens
Q Kahn's algorithm on a graph of 5 steps empties its queue after placing 3. What does that tell you?
Answer: C
Every step that can be placed is placed. If some are left, each of them still waits for another step that is left. That is a cycle.
Whenever two vertices are in the queue at once, either can go first. The two choices lead to different valid orders. On the build map, 1 and 2 are both ready after step 0, so 0, 1, 2, ... and 0, 2, 1, ... are both fine.
An order is unique only when exactly one vertex is ready at every step. That happens when the graph holds one long chain that touches every vertex.
Often you need one fixed answer, for a test or so that two runs agree. Then pick a rule for the ties: the smallest number first, or the first name in alphabetical order. For that, hold the ready vertices in a min-heap instead of a plain queue, as in Heaps and priority queues (S5).
Here is Kahn's algorithm as code. It returns an order, or an empty list when there is a cycle. The step markers [1] to [6] match the steps in the player. The queue is first in, first out, as in the lesson.
from collections import deque
def topo_kahn(n, edges):
# [1] Build the lists of arrows, and count each vertex's in-degree.
after = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges:
after[a].append(b)
indeg[b] += 1
# [2] Every vertex with in-degree 0 is ready: it joins the queue.
queue = deque(v for v in range(n) if indeg[v] == 0)
order = []
while queue:
# [3] Take the front vertex and put it next in the order.
v = queue.popleft()
order.append(v)
# [4] Remove its arrows. A vertex that reaches in-degree 0 is ready.
for u in after[v]:
indeg[u] -= 1
if indeg[u] == 0:
queue.append(u)
# [5] Fewer than n placed: the rest wait on each other, a cycle.
# [6] Otherwise the order is complete.
return order if len(order) == n else []public int[] topoKahn(int n, int[][] edges) {
// [1] Build the lists of arrows, and count each vertex's in-degree.
java.util.List<Integer>[] after = new java.util.List[n];
for (int i = 0; i < n; i++) after[i] = new java.util.ArrayList<>();
int[] indeg = new int[n];
for (int[] e : edges) {
after[e[0]].add(e[1]);
indeg[e[1]]++;
}
// [2] Every vertex with in-degree 0 is ready: it joins the queue.
java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>();
for (int v = 0; v < n; v++) if (indeg[v] == 0) queue.add(v);
int[] order = new int[n];
int placed = 0;
while (!queue.isEmpty()) {
// [3] Take the front vertex and put it next in the order.
int v = queue.poll();
order[placed++] = v;
// [4] Remove its arrows. A vertex that reaches in-degree 0 is ready.
for (int u : after[v]) {
indeg[u]--;
if (indeg[u] == 0) queue.add(u);
}
}
// [5] Fewer than n placed: the rest wait on each other, a cycle.
// [6] Otherwise the order is complete.
return placed == n ? order : new int[0];
}vector<int> topoKahn(int n, vector<vector<int>> edges) {
// [1] Build the lists of arrows, and count each vertex's in-degree.
vector<vector<int>> after(n);
vector<int> indeg(n, 0);
for (auto& e : edges) {
after[e[0]].push_back(e[1]);
indeg[e[1]]++;
}
// [2] Every vertex with in-degree 0 is ready: it joins the queue.
queue<int> ready;
for (int v = 0; v < n; v++) if (indeg[v] == 0) ready.push(v);
vector<int> order;
while (!ready.empty()) {
// [3] Take the front vertex and put it next in the order.
int v = ready.front();
ready.pop();
order.push_back(v);
// [4] Remove its arrows. A vertex that reaches in-degree 0 is ready.
for (int u : after[v]) {
indeg[u]--;
if (indeg[u] == 0) ready.push(u);
}
}
// [5] Fewer than n placed: the rest wait on each other, a cycle.
// [6] Otherwise the order is complete.
if ((int)order.size() != n) return {};
return order;
}function topoKahn(n, edges) {
// [1] Build the lists of arrows, and count each vertex's in-degree.
const after = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const [a, b] of edges) {
after[a].push(b);
indeg[b]++;
}
// [2] Every vertex with in-degree 0 is ready: it joins the queue.
const queue = [];
for (let v = 0; v < n; v++) if (indeg[v] === 0) queue.push(v);
const order = [];
for (let head = 0; head < queue.length; head++) {
// [3] Take the front vertex and put it next in the order.
const v = queue[head];
order.push(v);
// [4] Remove its arrows. A vertex that reaches in-degree 0 is ready.
for (const u of after[v]) {
indeg[u]--;
if (indeg[u] === 0) queue.push(u);
}
}
// [5] Fewer than n placed: the rest wait on each other, a cycle.
// [6] Otherwise the order is complete.
return order.length === n ? order : [];
}On the build map this returns 0, 1, 2, 4, 3, 5. Python's deque makes taking from the front cheap, while pop(0) on a list shifts every item. JavaScript avoids the problem by keeping a head index instead of removing items.
Exercise · Find the bug: The build that reports a loop for no reason. On some maps with no cycle, this version returns an empty list as if there were one. Which line is wrong?
def topo_kahn(n, edges):
after = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges:
after[a].append(b)
indeg[b] += 1
queue = deque([0])
order = []
while queue:
v = queue.popleft()
order.append(v)
for u in after[v]:
indeg[u] -= 1
if indeg[u] == 0:
queue.append(u)
return order if len(order) == n else []And here is the DFS method. It walks each vertex once. A vertex has one of three marks: 0 not started, 1 in progress, 2 finished.
def visit_topo(v, after, state, finished):
# [1] Mark it in progress, and visit everything that comes after it.
state[v] = 1
for u in after[v]:
if state[u] == 1:
return False
if state[u] == 0 and not visit_topo(u, after, state, finished):
return False
# [2] Nothing is left to visit: it is finished. Write it down.
state[v] = 2
finished.append(v)
return True
def topo_dfs(n, edges):
# [3] Build the lists of arrows. Every vertex starts as not started (0).
after = [[] for _ in range(n)]
for a, b in edges:
after[a].append(b)
state = [0] * n
finished = []
for v in range(n):
if state[v] == 0 and not visit_topo(v, after, state, finished):
# [4] A vertex reached while in progress: a cycle.
return []
# [5] The reverse of the finish order is a valid order.
return finished[::-1]private boolean visitTopo(int v, java.util.List<Integer>[] after, int[] state, int[] finished, int[] count) {
// [1] Mark it in progress, and visit everything that comes after it.
state[v] = 1;
for (int u : after[v]) {
if (state[u] == 1) return false;
if (state[u] == 0 && !visitTopo(u, after, state, finished, count)) return false;
}
// [2] Nothing is left to visit: it is finished. Write it down.
state[v] = 2;
finished[count[0]++] = v;
return true;
}
public int[] topoDfs(int n, int[][] edges) {
// [3] Build the lists of arrows. Every vertex starts as not started (0).
java.util.List<Integer>[] after = new java.util.List[n];
for (int i = 0; i < n; i++) after[i] = new java.util.ArrayList<>();
for (int[] e : edges) after[e[0]].add(e[1]);
int[] state = new int[n];
int[] finished = new int[n];
int[] count = new int[1];
for (int v = 0; v < n; v++) {
if (state[v] == 0 && !visitTopo(v, after, state, finished, count)) {
// [4] A vertex reached while in progress: a cycle.
return new int[0];
}
}
// [5] The reverse of the finish order is a valid order.
int[] order = new int[n];
for (int i = 0; i < n; i++) order[i] = finished[n - 1 - i];
return order;
}bool visitTopo(int v, vector<vector<int>>& after, vector<int>& state, vector<int>& finished) {
// [1] Mark it in progress, and visit everything that comes after it.
state[v] = 1;
for (int u : after[v]) {
if (state[u] == 1) return false;
if (state[u] == 0 && !visitTopo(u, after, state, finished)) return false;
}
// [2] Nothing is left to visit: it is finished. Write it down.
state[v] = 2;
finished.push_back(v);
return true;
}
vector<int> topoDfs(int n, vector<vector<int>> edges) {
// [3] Build the lists of arrows. Every vertex starts as not started (0).
vector<vector<int>> after(n);
for (auto& e : edges) after[e[0]].push_back(e[1]);
vector<int> state(n, 0);
vector<int> finished;
for (int v = 0; v < n; v++) {
if (state[v] == 0 && !visitTopo(v, after, state, finished)) {
// [4] A vertex reached while in progress: a cycle.
return {};
}
}
// [5] The reverse of the finish order is a valid order.
reverse(finished.begin(), finished.end());
return finished;
}function visitTopo(v, after, state, finished) {
// [1] Mark it in progress, and visit everything that comes after it.
state[v] = 1;
for (const u of after[v]) {
if (state[u] === 1) return false;
if (state[u] === 0 && !visitTopo(u, after, state, finished)) return false;
}
// [2] Nothing is left to visit: it is finished. Write it down.
state[v] = 2;
finished.push(v);
return true;
}
function topoDfs(n, edges) {
// [3] Build the lists of arrows. Every vertex starts as not started (0).
const after = Array.from({ length: n }, () => []);
for (const [a, b] of edges) after[a].push(b);
const state = new Array(n).fill(0);
const finished = [];
for (let v = 0; v < n; v++) {
if (state[v] === 0 && !visitTopo(v, after, state, finished)) {
// [4] A vertex reached while in progress: a cycle.
return [];
}
}
// [5] The reverse of the finish order is a valid order.
return finished.reverse();
}The finish order on the build map is 5, 3, 4, 1, 2, 0, so the code returns 0, 2, 1, 4, 3, 5. It is a different valid order from Kahn's. The recursion goes as deep as the longest chain, so for a chain of 100,000 steps use Kahn's, or write the DFS with your own stack.
Predict what happens
Q Both methods run on the same graph. Kahn gives 0, 1, 2, 4, 3, 5. The DFS method gives 0, 2, 1, 4, 3, 5. Is one of them wrong?
Answer: C
Every arrow points forward in both orders. Steps 1 and 2 are independent, so either can go first. The order is not unique.
Now write the sort yourself, for a build tool. The lab has one function. Each test gives it a number of steps and a list of rules, and checks the order it returns.
topo_order(n, edges): return a list of all n steps in an order where every rule [before, after] has before earlier than after. Return an empty list [] when no such order exists, because of a cycle.When several steps are ready at the same time, take the smallest number first. Then there is exactly one right answer for each map, and the tests can check it.
Three rules keep it correct:
n at the end. A shorter order means a cycle: return [].Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Kahn's algorithm | The DFS method |
|---|---|---|
| Time | O(n + m): every step enters the queue once and every rule is removed once | O(n + m): every step is visited once and every rule is followed once |
| Memory | O(n + m) for the lists, the in-degrees and the queue | O(n + m), plus the recursion, which can be n deep |
| Finds a cycle | The order is shorter than n | A step is reached while still in progress |
| Smallest-first ties | A min-heap: O((n + m) log n) | Not natural: use Kahn's |
For 100,000 steps and 200,000 rules, both finish in a few hundred thousand steps. The sort is never the slow part of a build.
Use topological sort whenever tasks have rules of the form "this must come before that". Build steps, course prerequisites, install order for packages, spreadsheet cells and pipeline stages all fit. It also answers "is this set of rules even possible?" for free: a cycle means no.
Use Kahn's algorithm when you also want to know which steps could run at the same time, because they sit in the queue together. Use it too when the chain is very long.
Do not expect an answer when the graph has a cycle: there is none. Report the cycle instead, and ask someone to break a rule.
Do not use it when you only need to sort by a number, such as a price or a date. Sorting does that. A topological sort is for rules between pairs of items.
A rule [0, 1] means 0 comes first, so the arrow goes from 0 to 1: after[a].append(b) and indeg[b] += 1. Flip both lines and every answer comes out reversed. Flip only indeg[a] += 1, and the counts no longer match the arrows, so the order comes out wrong. Say the rule out loud: before, then after.
A step that appears in no rule still has to be in the order. for v in range(n) finds it, because its in-degree is 0. A loop over for a, b in edges never sees it, and the order comes out too short.
Always compare the length of the order with n: with a cycle Kahn's loop still ends, but with fewer steps than the graph has.
If the graph has a cycle, Kahn's loop still ends, with fewer than n steps. return order hands the caller half a build as if it were complete. Write return order if len(order) == n else [].
A test such as assert result == [0, 1, 2, 4, 3, 5] fails on the valid order [0, 2, 1, 3, 4, 5]. Either check that every rule points forward, or fix a tie-break rule such as the smallest number first and use it every time.
In the DFS method, if state[u] != 0: return False treats a finished step as a cycle. A step reached again after it finished is only a second way to the same step. Only state[u] == 1, in progress, closes a cycle.
Explain the two methods in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Rules and orders
Q1/2 A build has the rules "install before compile" and "compile before test". Which graph arrow does "compile before test" give?
Answer: B
A rule "before, then after" is an arrow from the first step to the second. It raises the in-degree of the step that must wait.
Q2/2 For which graph does a topological order exist?
Answer: C
A cycle has no first step, because every step on it waits for another step on it. Without a cycle, an order always exists.
Checkpoint · Kahn's algorithm
Q1/2 What is the in-degree of a step in a dependency graph?
Answer: B
In-degree counts arrows that point at a vertex. In a dependency graph those are the steps it waits for. Zero means it can go now.
Q2/2 Kahn's algorithm takes step 4 from the queue. Step 7 has in-degree 2, and there is an arrow from 4 to 7. What happens?
Answer: B
Removing the arrow lowers the in-degree by one. Step 7 joins the queue only when its in-degree reaches 0.
Checkpoint · Cycles
Q1/2 Kahn's algorithm on 7 steps ends with 4 in the order. What do you report?
Answer: B
Steps that never reach in-degree 0 each wait for another step that is left. That is a cycle, and the answer must say so.
Q2/2 In the DFS method, when does reaching a step mean a cycle?
Answer: C
A step reached again after it finished is a second way to the same step, which is fine. Only a step still in progress closes a loop.
Checkpoint · The DFS method
Q1/2 In the DFS method, a step is written down when it finishes. What is true at that moment?
Answer: B
A step finishes after everything it points at. Reversing the list then puts it before all of them.
Q2/2 The finish order of the DFS method on a graph is 4, 2, 3, 1, 0. What is the topological order?
Answer: B
The topological order is the finish order reversed: 0, 1, 3, 2, 4.
Checkpoint · Ties and cost
Q1/2 You need the same order every run, with the smallest number first among the ready steps. What do you change in Kahn's algorithm?
Answer: B
A queue gives first in, first out, which can differ from smallest first. A min-heap always gives the smallest ready step.
Q2/2 What is the time of Kahn's algorithm on n steps and m rules, with a plain queue?
Answer: C
Every step enters the queue once and every rule is removed once. The log n appears only with a heap for ties.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.