Topological Sort
How to order tasks so that each one comes after the tasks it depends on, how to detect a cycle, and what interviewers ask about it.
On this page
A topological sort puts the nodes of a directed graph in a line so that every edge points from an earlier node to a later one. You use it when the edges are "must happen before" rules, such as tasks with prerequisites, and you need an order in which everything can be done. The same algorithm also tells you when no such order exists, because the rules contain a cycle.
Without it, you would have to guess an order and check every rule, and you would have no way to tell a bad guess from a set of rules that cannot be satisfied at all. The running example in this lesson is making a pizza: toppings need the dough, the sauce and the cheese, baking needs the toppings and a hot oven, and eating needs the baked pizza.
A graph usually has more than one valid order. Dough, sauce, cheese, oven, toppings, bake, eat is valid, and so is oven, cheese, sauce, dough, toppings, bake, eat. A valid order exists exactly when the graph has no cycle, that is, when it is a DAG (directed acyclic graph). If toppings needed bake and bake needed toppings, neither could ever start.
How Kahn's algorithm works
The in-degree of a node is the number of edges pointing into it, which is the number of tasks it is still waiting for. A node with in-degree 0 can be done right now. Kahn's algorithm repeatedly takes such a node, puts it next in the order, and removes its outgoing edges.
- Compute the in-degree of every node and put the nodes with in-degree 0 in a queue.
- Take a node from the queue and append it to the order.
- For each node that the taken node points to, subtract 1 from its in-degree. If it reaches 0, add it to the queue.
- Repeat until the queue is empty. If the order contains every node, it is a valid topological order. If it is shorter, the graph has a cycle.
This looks like breadth-first search, with one difference: a node joins the queue only when its last prerequisite has been taken, not when it is first seen. Nodes on a cycle wait for each other, so their in-degree never reaches 0 and they never enter the queue. That is why a short order means a cycle.
count incoming arrows (in) for every taskready = tasks with in = 0while ready is not empty: take a task, append it to order for each task after it: in = in - 1, if 0: add to readyorder has every task? done : there is a cycle- ready queue0D1S2C3Oorder
1The in-degrees are counted. D, S, C and O have no incoming arrows, so they start in the ready queue.
- ready queue0S1C2Oorder0D
2D is taken. Its arrow to T is removed, so T now waits on 2 tasks instead of 3.
- ready queue0C1Oorder0D1S
3S is taken, and T drops to 1. T is still waiting for C, so it does not join the queue.
- ready queue0O1Torder0D1S2C
4C is taken. T drops to 0, because its last prerequisite is done, and T joins the ready queue.
- ready queue0Torder0D1S2C3O
5O is taken, and B drops to 1. B still has to wait for T.
- ready queue0Border0D1S2C3O4T
6T is taken. B drops to 0 and becomes ready.
- ready queue0Eorder0D1S2C3O4T5B
7B is taken. E drops to 0 and becomes ready.
- ready queueorder0D1S2C3O4T5B6E
8E is taken. It points to no other task, and the queue is now empty.
- ready queueorder0D1S2C3O4T5B6E
9All 7 tasks are in the order, so there is no cycle, and every arrow points forward. Each task was taken once and each of the 6 arrows was removed once.
Code for Kahn's algorithm
The function returns the order, or null (None in Python) when the length check shows a cycle.
// rules: list of [before, after] pairs.
function taskOrder(tasks, rules) {
const next = {};
const inDegree = {};
for (const t of tasks) { next[t] = []; inDegree[t] = 0; }
for (const [before, after] of rules) {
next[before].push(after);
inDegree[after]++;
}
const queue = tasks.filter((t) => inDegree[t] === 0);
const order = [];
let head = 0;
while (head < queue.length) {
const task = queue[head++];
order.push(task);
for (const after of next[task]) {
inDegree[after]--;
if (inDegree[after] === 0) queue.push(after); // last blocker gone
}
}
return order.length === tasks.length ? order : null; // null: cycle
}
taskOrder(
["dough", "sauce", "cheese", "oven", "toppings", "bake", "eat"],
[["dough", "toppings"], ["sauce", "toppings"], ["cheese", "toppings"],
["toppings", "bake"], ["oven", "bake"], ["bake", "eat"]]
); // ["dough", "sauce", "cheese", "oven", "toppings", "bake", "eat"]from collections import deque
# rules: list of (before, after) pairs.
def task_order(tasks, rules):
nxt = {t: [] for t in tasks}
in_degree = {t: 0 for t in tasks}
for before, after in rules:
nxt[before].append(after)
in_degree[after] += 1
queue = deque(t for t in tasks if in_degree[t] == 0)
order = []
while queue:
task = queue.popleft()
order.append(task)
for after in nxt[task]:
in_degree[after] -= 1
if in_degree[after] == 0:
queue.append(after) # last blocker gone
return order if len(order) == len(tasks) else None # None: cycle
task_order(
["dough", "sauce", "cheese", "oven", "toppings", "bake", "eat"],
[("dough", "toppings"), ("sauce", "toppings"), ("cheese", "toppings"),
("toppings", "bake"), ("oven", "bake"), ("bake", "eat")],
) # ['dough', 'sauce', 'cheese', 'oven', 'toppings', 'bake', 'eat']Counting in-degrees reads every rule once, each node enters the queue once, and each edge is removed once. The lists of next tasks hold E entries.
Variants and when to use each
Topological sort with DFS
A depth-first search call on a node returns only after every node reachable from it has finished, and those are exactly the nodes that must come after it. So you record each node when its call finishes and reverse the list at the end.
Cycle detection needs a third state. Each node is unvisited, on the current path (its call has started but not returned), or finished. If the search reaches a node that is on the current path, it has followed edges in a circle, and no valid order exists. A plain visited flag is not enough, because reaching a finished node is normal and reaching a node on the current path is a cycle.
function taskOrderDfs(tasks, rules) {
const next = {};
for (const t of tasks) next[t] = [];
for (const [before, after] of rules) next[before].push(after);
const state = {}; // undefined: unvisited, 1: on the path, 2: finished
const finished = [];
function visit(task) {
if (state[task] === 2) return true;
if (state[task] === 1) return false; // back on our own path: cycle
state[task] = 1;
for (const after of next[task]) {
if (!visit(after)) return false;
}
state[task] = 2;
finished.push(task); // everything after it is already finished
return true;
}
for (const t of tasks) {
if (!visit(t)) return null;
}
return finished.reverse();
}
// pizza tasks → ["oven", "cheese", "sauce", "dough", "toppings", "bake", "eat"]def task_order_dfs(tasks, rules):
nxt = {t: [] for t in tasks}
for before, after in rules:
nxt[before].append(after)
state = {} # missing: unvisited, 1: on the path, 2: finished
finished = []
def visit(task):
if state.get(task) == 2:
return True
if state.get(task) == 1:
return False # back on our own path: cycle
state[task] = 1
for after in nxt[task]:
if not visit(after):
return False
state[task] = 2
finished.append(task) # everything after it is already finished
return True
for t in tasks:
if not visit(t):
return None
return finished[::-1]
# pizza tasks → ['oven', 'cheese', 'sauce', 'dough', 'toppings', 'bake', 'eat']On the pizza tasks, the search starts at dough and goes through toppings and bake to eat. Eat finishes first, then bake, toppings and dough, and then sauce, cheese and oven each finish immediately. Reversed, that gives oven, cheese, sauce, dough, toppings, bake, eat, which is a different order from Kahn's but equally valid. Both versions run in O(V + E). Kahn's algorithm needs no recursion, so it is safer on very deep graphs, and the DFS version is convenient when you are already writing a DFS for something else.
A specific order, such as the smallest one
When a problem asks for the alphabetically smallest valid order, or for the order that does the most important task first, replace the plain queue in Kahn's algorithm with a priority queue of the ready nodes. Each step then takes the best ready node instead of the oldest one. Taking the smallest ready node each time gives the smallest valid order, because any node that is ready now could be placed first, and the smallest of them is the best choice for the first position. The cost rises to O((V + E) log V) because of the heap operations.
Processing in rounds
Some problems ask how many rounds are needed if every ready task can run at the same time, for example the minimum number of semesters to finish all courses. Run Kahn's algorithm one level at a time: take everything that is in the queue now as one round, then collect the nodes that became ready as the next round. The number of rounds is the number of nodes on the longest chain of dependencies. In the pizza example there are four rounds: dough, sauce, cheese and oven; then toppings; then bake; then eat.
When topological sort does not apply
It only applies to directed graphs. An undirected edge has no direction, so it gives no "before" and "after". If the graph has a cycle there is no answer, and the algorithm can only report that. If a problem asks for a grouping of nodes that depend on each other in a cycle, that is a different problem, strongly connected components, which needs a different algorithm. If the edges are not ordering rules at all, for example "are these two nodes connected", use Union-Find or a plain graph search.
Pitfalls and nuances
In the interview
Topological sort is the answer when a problem gives you items and pairwise rules saying that one must come before another, and asks for an order, for whether an order exists, or for how long it takes. Typical wordings are course prerequisites, build or install dependencies, task scheduling, and recovering an alphabet from a list of words sorted in an unknown alphabet. The signal is a directed relationship between items together with the question "is there a valid order". Say the words "this is a directed graph and I need a topological order" early, and state which direction your edges go.
Questions to expect:
- "How do you detect a cycle?" With Kahn's algorithm, a cycle exists exactly when the order contains fewer nodes than the graph, because nodes on a cycle never reach in-degree 0. With DFS, a cycle exists when the search reaches a node that is still on the current path.
- "Why does Kahn's algorithm work?" A node with in-degree 0 has no prerequisites left, so it is safe to place next. Removing it can only free other nodes, and if a node remains but none has in-degree 0, every remaining node is waiting for another remaining node, which means a cycle.
- "What is the complexity?" It is O(V + E) time and space for both versions. Each node is processed once and each edge is looked at once, and the graph itself takes O(V + E) space.
- "Is the answer unique?" Usually not. The order is unique only when exactly one node is ready at every step, so you can check it by watching whether the queue ever holds two nodes at once.
- "How would you get the lexicographically smallest order?" Use a priority queue of the ready nodes in place of the plain queue, and always take the smallest. This costs an extra log factor.
- "How many rounds if independent tasks run in parallel?" Process the queue one level at a time and count the levels. The count equals the length of the longest dependency chain.
- "Why not use recursion?" A long dependency chain can overflow the call stack in the DFS version, so Kahn's algorithm is the safer choice when the input size is not bounded.
Using the pizza rules, which of these is not a valid order?
You run Kahn's algorithm on 6 tasks and the order contains only 4 of them. What does that tell you?
A problem asks for the alphabetically smallest valid order of the tasks. What do you change in Kahn's algorithm?
What to practise next
Read Union-Find for connectivity questions while edges keep arriving, and Dijkstra's algorithm for shortest paths when edges have weights.