Topological sort explained, with Kahn's algorithm and DFS
A topological sort lists the nodes of a directed graph so that every edge points forward: if a must come before b, a appears earlier. It exists only when the graph has no cycle. Kahn's algorithm builds it by repeatedly taking a node with no unmet prerequisites (in-degree zero) and removing its outgoing edges; a DFS builds it by recording each node when it finishes and reversing that list. Both run in O(V + E), and both detect a cycle when some nodes can never be placed.
By Evin JohnPublished 9 min read
The task, stated for this page
There are n tasks, numbered 0 to n - 1, and a list of pairs [a, b] meaning task a must be finished before task b starts. Return an order in which to do all n tasks that respects every pair. If no such order exists, because the rules go round in a circle, return an empty list. Pairs may repeat, and any valid order is accepted unless the question asks for a specific one.
| Task | Name | Must come after |
|---|---|---|
| 0 | Write the database migration | nothing |
| 1 | Design the API | nothing |
| 2 | Build the client | 1 |
| 3 | Build the server | 0 and 1 |
| 4 | Run integration tests | 2 and 3 |
| 5 | Ship the release | 4 |
The pairs are [0, 3], [1, 3], [3, 4], [2, 4], [1, 2] and [4, 5]. Valid orders include 0, 1, 3, 2, 4, 5 and 1, 2, 0, 3, 4, 5; both put every task after the ones it depends on. If you added the pair [5, 1], shipping would have to come before designing the API, which must come before shipping. That is a cycle, so the answer would be empty.
Where it shows up in interviews
Topological sort is rarely asked by name. It hides behind course prerequisites, build systems, package dependencies, spreadsheet formulas that refer to other cells, or recovering an alphabet's letter order from a list of words sorted in that alphabet. The common follow-ups ask whether an order exists at all (cycle detection), the smallest order when ties are broken by number, or how many stages are needed when independent tasks can run at the same time. Spotting the dependency graph is half the work.
Kahn's algorithm
Count, for each task, how many prerequisites it is still waiting on. Every task with a count of zero can start now, so put them in a queue. Take one out, append it to the order, and for each task that depended on it, lower that task's count by one. Any count that drops to zero joins the queue. When the queue is empty, either all n tasks are in the order, or the leftovers are each waiting on something in a cycle.
from collections import deque
def topo_order(n, before):
# before: pairs [a, b] meaning task a must happen before task b
after = [[] for _ in range(n)]
waiting_on = [0] * n # in-degree: unmet prerequisites
for a, b in before:
after[a].append(b)
waiting_on[b] += 1
ready = deque(t for t in range(n) if waiting_on[t] == 0)
order = []
while ready:
t = ready.popleft()
order.append(t)
for nxt in after[t]:
waiting_on[nxt] -= 1
if waiting_on[nxt] == 0:
ready.append(nxt)
return order if len(order) == n else [] # leftovers sit on a cycleOn the release example the queue starts with 0 and 1. Popping 0 lowers task 3 to one remaining prerequisite. Popping 1 frees both 3 and 2. Then 3 and 2 come out, which frees 4, and 4 frees 5. The order is 0, 1, 3, 2, 4, 5. Repeated pairs are harmless: each copy adds one to the count and each copy takes one away.
DFS with three colours
The depth-first version uses the fact that a task can only finish after everything reachable from it has finished. Mark each task white (not seen), grey (on the current path) or black (finished). When a task turns black, append it to a list; that list, reversed, is a valid order. If the search ever follows an edge into a grey task, it has found a path that loops back on itself, so there is a cycle. The version below keeps its own stack instead of recursing, so a long chain cannot overflow Python's call stack.
def topo_order_dfs(n, before):
after = [[] for _ in range(n)]
for a, b in before:
after[a].append(b)
WHITE, GREY, BLACK = 0, 1, 2 # unvisited, on the current path, finished
color = [WHITE] * n
finished = []
for root in range(n):
if color[root] != WHITE:
continue
color[root] = GREY
stack = [(root, 0)] # (task, index of the next edge to try)
while stack:
t, i = stack[-1]
if i < len(after[t]):
stack[-1] = (t, i + 1)
nxt = after[t][i]
if color[nxt] == GREY:
return [] # an edge back onto the current path: a cycle
if color[nxt] == WHITE:
color[nxt] = GREY
stack.append((nxt, 0))
else:
color[t] = BLACK
finished.append(t) # every task after t is already finished
stack.pop()
return finished[::-1]On the release example this returns 1, 2, 0, 3, 4, 5, a different but equally valid order. Two colours are not enough: a black task reached again is fine (it was finished by another branch), and only a grey one signals a cycle. A self-loop such as [1, 1] is caught by the same check, since task 1 is grey when its own edge is examined.
Variants that come up
The smallest valid order
If ties must be broken by the smallest task number, replace Kahn's queue with a min-heap. Each step takes the smallest task that is ready. For the release example that gives 0, 1, 2, 3, 4, 5. The cost rises to O(V log V + E) because of the heap.
import heapq
def smallest_order(n, before):
after = [[] for _ in range(n)]
waiting_on = [0] * n
for a, b in before:
after[a].append(b)
waiting_on[b] += 1
ready = [t for t in range(n) if waiting_on[t] == 0]
heapq.heapify(ready) # always take the smallest ready task
order = []
while ready:
t = heapq.heappop(ready)
order.append(t)
for nxt in after[t]:
waiting_on[nxt] -= 1
if waiting_on[nxt] == 0:
heapq.heappush(ready, nxt)
return order if len(order) == n else []Parallel rounds
If every ready task can run at the same time, process Kahn's in layers: all current zeros form one round, and the tasks they free form the next. The number of rounds equals the number of tasks on the longest dependency chain. The release example needs four rounds: {0, 1}, then {3, 2}, then {4}, then {5}.
function buildRounds(n, before) {
// returns the tasks grouped into rounds that can run in parallel, or null on a cycle
const after = Array.from({ length: n }, () => []);
const waitingOn = new Array(n).fill(0);
for (const [a, b] of before) {
after[a].push(b);
waitingOn[b] += 1;
}
let current = [];
for (let t = 0; t < n; t++) if (waitingOn[t] === 0) current.push(t);
const rounds = [];
let done = 0;
while (current.length > 0) {
rounds.push(current);
done += current.length;
const next = [];
for (const t of current) {
for (const nxt of after[t]) {
waitingOn[nxt] -= 1;
if (waitingOn[nxt] === 0) next.push(nxt);
}
}
current = next;
}
return done === n ? rounds : null;
}Building each round as a fresh array avoids shift, which moves every element of a JavaScript array. For a single-queue version in JavaScript, keep a head index into an array and advance it instead of removing from the front.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Kahn's algorithm | O(V + E) | O(V + E) for the lists, O(V) for counts and queue |
| DFS with three colours | O(V + E) | O(V + E), with an O(V) stack |
| Smallest order with a heap | O(V log V + E) | O(V + E) |
| Parallel rounds | O(V + E) | O(V + E) |
| Try every ordering | O(V! · E) | O(V) |
Edge cases to test
- No rules at all: every order is valid, and Kahn's returns 0 to n - 1.
- A task that depends on itself: a cycle of length one.
- A cycle in one part of the graph and a valid chain elsewhere: the answer is still empty.
- The same rule listed twice.
- Isolated tasks with no rules in either direction: they must still appear.
- A long chain, which breaks recursive DFS in Python at its default recursion limit.
Mistakes
- Reversing the edge direction, which produces a valid order for the opposite rules.
- Forgetting to check that all V tasks were placed, and returning a partial order on a cycle.
- In DFS, using one visited flag and reporting a cycle whenever a visited node is reached again.
- Returning the DFS finishing order without reversing it.
- Starting the queue with only task 0 instead of every task with in-degree zero.
- Using shift in a JavaScript loop over a very large queue.
How to explain it out loud
Fictional example
- Candidate
- Each rule says one task comes before another, so I'll draw an edge from the earlier task to the later one. An order exists exactly when this graph has no cycle.
- Candidate
- I'll use Kahn's algorithm: count unmet prerequisites per task, start with every task at zero, and each time I place a task, lower the counts of the tasks after it.
- Interviewer
- How do you know if there's a cycle?
- Candidate
- If the queue empties before I've placed all n tasks, the rest are waiting on each other. That's linear in tasks plus rules. If ties should go to the smallest number, I'd swap the queue for a min-heap.
Related problems
The in-degree counts are the same numbers used in Find the Town Judge. Cost reasoning for graph traversals, O(V + E) rather than O(V), is covered in the Big O cheat sheet. For undirected connectivity instead of ordering, see Accounts Merge; for a weighted path on a grid, Swim in Rising Water; and for scheduling with cooldowns rather than dependencies, Task Scheduler. Longest Increasing Path in a Matrix uses the layered version of Kahn's algorithm on a grid, and Keys and Rooms is a gentle warm-up on directed reachability.
Practicing it with Natively
Topological sort questions rarely say the name, so practice is mostly about recognising them. Natively can read a dependency-style prompt from a screenshot on Mac or Windows and suggest an approach and code in its overlay, which shows quickly whether you spotted the graph. In a mock interview spoken aloud, its transcript lets you check afterwards that you explained the cycle check. See the AI interview assistant for more.
Questions people ask
What is a topological sort?
An ordering of the nodes of a directed graph in which every edge points from an earlier node to a later one. It exists only if the graph has no cycle.
How does Kahn's algorithm work?
Count each node's incoming edges, start a queue with every node at zero, then repeatedly remove a node, append it to the order and lower its neighbours' counts, adding any that reach zero.
How do you detect a cycle with topological sort?
In Kahn's algorithm, a cycle exists if fewer than V nodes get placed. In DFS, a cycle exists if you follow an edge into a node that is still on the current path.
What is the time complexity of topological sort?
O(V + E) for both Kahn's algorithm and DFS. Breaking ties with a min-heap for the smallest order raises it to O(V log V + E).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
