Topological sort
medium 20 minA topological sort lists the nodes of a directed graph so that every edge u → v has u before v: a valid order for tasks with prerequisites.
See it run
Order the nodes of a DAG so every arrow points forward: peel off zero in-degree nodes with Kahn's queue, or reverse a DFS finish order, and catch cycles on the way.
Operations
Kahn's algorithm
Count each node's prerequisites (its in-degree), start with the nodes that have none, and every time a node is output, knock one off each of its successors.
Step 1 of 11
Five courses and their prerequisites
An arrow u → v means take u before v. CS101 opens CS102 and CS201, Math also opens CS201, and CS301 needs both CS102 and CS201. We want an order of all five that never breaks an arrow.
Step 1: Five courses and their prerequisites
from collections import dequedef kahn(n, adj): indeg = [0] * n for u in range(n): for v in adj[u]: indeg[v] += 1 # one more prerequisite queue = deque(u for u in range(n) if indeg[u] == 0) order = [] while queue: u = queue.popleft() # ready: nothing left before it order.append(u) for v in adj[u]: indeg[v] -= 1 # u is done, so v waits on one less if indeg[v] == 0: queue.append(v) return order if len(order) == n else [] # short = cycle- Time
- O(V + E)
- Space
- O(V)
- Cycle check
- output count < V
- Order
- direct, no reversal
Use `collections.deque` and `popleft()`. A plain list with `pop(0)` shifts every element and turns the O(V + E) algorithm into O(V²) on long chains.
In the real world
The same topological sort doing real jobs. Pick one and step through it.
Compile every module after the modules it imports. Arrows point from a dependency to the module that needs it, so Kahn's order is a compile order.
Step 1 of 6
Six modules
log and db feed utils; db feeds api; utils, conf and api feed main. In-degrees: main 3, utils 2, api 1, the rest 0.
Step 1: Six modules
from graphlib import TopologicalSorterneeds = {"utils": ["log", "db"], "api": ["db"], "main": ["utils", "conf", "api"]}order = list(TopologicalSorter(needs).static_order())print(order) # dependencies always come before what needs themCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Building the edges backwards
criticalCourse lists usually give pairs [course, prerequisite]: the prerequisite comes first, so the edge is prerequisite → course. Reversing it silently produces the reverse order, which breaks every rule.
Wrongfor course, pre in prerequisites: adj[course].append(pre) indeg[pre] += 1Rightfor course, pre in prerequisites: adj[pre].append(course) # pre must come first indeg[course] += 1One visited set for directed cycle detection
criticalWith only seen / not seen, reaching a node finished on another branch looks like a cycle. In the course graph CS201 → CS301 would be a false alarm. You need GRAY (on the path) separate from BLACK (finished).
Wrongdef dfs(u): if u in visited: return True # cycle? not necessarily visited.add(u) return any(dfs(v) for v in adj[u])Rightdef dfs(u): color[u] = GRAY for v in adj[u]: if color[v] == GRAY: return True # back edge: real cycle if color[v] == WHITE and dfs(v): return True color[u] = BLACK return FalseReturning Kahn's order without the count check
majorOn a cyclic graph Kahn simply stops early. Without comparing the length to n you return a partial list that looks like an answer.
Wrongwhile queue: ...return orderRightwhile queue: ...return order if len(order) == n else []Forgetting to reverse the DFS finish order
majorWith arrows pointing from first to later, post-order lists the last node first. Returned as is, it is a valid order of the reversed graph, the opposite of what was asked.
Wrongfor u in range(n): if color[u] == WHITE: dfs(u)return postRightfor u in range(n): if color[u] == WHITE: dfs(u)return post[::-1]Starting DFS only from in-degree 0 nodes
majorA component that is one pure cycle has no in-degree 0 node, so DFS never enters it and the cycle is never reported. Start from every WHITE node.
Wrongfor u in range(n): if indeg[u] == 0: dfs(u)Rightfor u in range(n): if color[u] == WHITE: dfs(u)Using a list as Kahn's queue
minorlist.pop(0) shifts every remaining item, O(n) per pop. On a long chain that makes the whole sort O(V²). deque.popleft is O(1).
Wrongqueue = [u for u in range(n) if indeg[u] == 0]u = queue.pop(0)Rightfrom collections import dequequeue = deque(u for u in range(n) if indeg[u] == 0)u = queue.popleft()
Interview tips
How to explain it
- A topological order lists the nodes of a directed graph so every edge u → v has u before v.
- It exists exactly when the graph is a DAG: directed with no cycle.
- Kahn: repeatedly output a node with in-degree 0 and decrement its successors. Fewer than V outputs means a cycle.
- DFS: record nodes as they finish; the reverse of that list is the order. An edge to a GRAY node means a cycle.
Clarify before coding
- Which way does each pair point? Write the edge as "first → later" before anything else.
- Return any valid order, or a specific one (lexicographically smallest needs a heap)?
- What to return on a cycle: empty list, False, or raise?
- Are all nodes listed, including ones with no edges at all?
The template
- adj = [[] for _ in range(n)]; indeg = [0] * n; for a, b in edges: adj[a].append(b); indeg[b] += 1
- queue = deque of every u with indeg[u] == 0; pop, append to order, decrement successors, push the new zeros.
- return order if len(order) == n else [].
- Min rounds: process the queue level by level and count the levels.
Facts to have ready
- Time O(V + E): each node is output once and each edge decremented once. Space O(V) beyond the graph.
- Every DAG has at least one source (in-degree 0) and one sink (out-degree 0).
- The order is unique exactly when Kahn's queue never holds two nodes at once (a Hamiltonian path).
- Python 3.9+ has graphlib.TopologicalSorter; it raises CycleError on a cycle.