Interview patterns
Topological Sort Explained: Kahn's Algorithm in Python
Updated Dec 4, 2026 · 3 min read
Topological sort puts the nodes of a directed graph in an order where every rule "a comes before b" holds. Kahn's algorithm counts each node's incoming arrows, starts with every node at zero, and keeps taking one out and lowering the count of everything it points to. If the final order is shorter than the number of nodes, the graph has a cycle and no valid order exists.

Key points
- ●Spot it when the problem has must-come-before rules: prerequisites, dependencies, build order.
- ●In-degree is the number of arrows coming into a node. Zero means nothing is blocking it.
- ●Take a zero node, add it to the order, and lower the in-degree of every node it points to.
- ●An order shorter than n means a cycle, so no valid order exists.
- ●It runs in O(V + E) time and space.

The problem you keep running into
You have 4 courses and a few rules: course 0 comes before courses 1 and 2, and both of those come before course 3. Which one do you take first, and what is a full order that breaks no rule?
The same shape hides in a lot of interview questions. Tasks with dependencies, packages to install, recipes that need other recipes, letters in an alien alphabet. Each time, the problem hands you pairs of "a must come before b" and asks for an order, or asks whether finishing everything is possible at all.
How to spot it
Three clues give it away:
- Things have to happen before other things: prerequisites, dependencies, build order.
- The question asks for a valid order, or whether you can finish everything.
- The rules form a directed graph, and a loop in the rules would make the job impossible.
When you see those, reach for topological sort.
The idea: count the arrows coming in
Draw each rule as an arrow from the first course to the second. A course's in-degree is how many arrows point into it, which is how many things still block it. A course with in-degree zero is free to take right now.
Kahn's algorithm turns that into a loop. Put every zero course in a queue. Take one out and add it to the order. Then knock one off the in-degree of every course it points to. Any course that drops to zero has just been unblocked, so it joins the queue. Repeat until the queue is empty.
Worked example
The rules are 0 before 1, 0 before 2, 1 before 3 and 2 before 3. The step table on the visual sheet above follows the same trace.
| Step | Take | In-degrees after | Queue |
|---|---|---|---|
| Start | none | 0:0, 1:1, 2:1, 3:2 | [0] |
| 1 | 0 | 1:0, 2:0, 3:2 | [1, 2] |
| 2 | 1 | 3:1 | [2] |
| 3 | 2 | 3:0 | [3] |
| 4 | 3 | none left | [] |
The order is 0, 1, 2, 3. It has 4 courses in it, the same as n, so every rule was satisfied.
Python template
from collections import deque
def topo(n, edges):
graph = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges: # a must come before b
graph[a].append(b)
indeg[b] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == n else [] # [] means a cycle
Run it on topo(4, [(0, 1), (0, 2), (1, 3), (2, 3)]) and you get [0, 1, 2, 3].
The catch: cycles
Change the rules to 0 before 1, 1 before 2 and 2 before 0. Every course now waits on another one, so none starts at in-degree zero. The queue starts empty, the loop never runs and the order stays empty. That's why the template ends with a length check: if the order is shorter than n, some courses never got unblocked, and they're the ones stuck in a cycle. Return an empty list, or false if the question only asks whether it's possible.
Complexity
Building the graph walks every edge once. The loop takes every node once and walks each of its outgoing edges once. That's O(V + E) time, and the adjacency list, in-degree list and queue take O(V + E) space.
Where it shows up
- LeetCode 207 Course Schedule: can you finish all courses? Check the length.
- LeetCode 210 Course Schedule II: return the order itself.
- LeetCode 269 Alien Dictionary: build arrows from neighbouring words, then sort the letters.
- LeetCode 2115 Find All Possible Recipes from Given Supplies: supplies start at zero, recipes unlock as their ingredients do.
Frequently asked questions
What is the time complexity of topological sort?
O(V + E). Building the graph touches every edge once, and the queue loop takes each node once and walks each of its outgoing edges once. The graph, the in-degree list and the queue take O(V + E) space.
How does topological sort detect a cycle?
Nodes on a cycle wait on each other, so their in-degree never reaches zero and they never enter the queue. When the loop ends, the order holds fewer than n nodes. That gap is the signal: return an empty list or false.
Kahn's algorithm or DFS for topological sort?
Both run in O(V + E). Kahn's algorithm uses a queue and in-degree counts, gives the order directly and finds cycles with one length check, so it is usually easier to get right in an interview. The DFS version adds a node after all its children and reverses the list at the end.
Can a graph have more than one topological order?
Yes. Whenever two nodes are at in-degree zero at the same time, either can go first. In the course example, 0, 2, 1, 3 is just as valid as 0, 1, 2, 3. Any answer that respects every rule is accepted.