Topological sort
We'll cover the following
Tasks have prerequisites written as "a>b" (a must come before b). Find an order that respects all of them.
Watch it run
Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.
in000
in011
in022
in133
in244
in255
in266
in277
in288
in199
in21010
in11111
Each label is the node's in-degree: how many prerequisites it still waits for. Nodes with in0 can start now.
queue [0, 1, 2]
1 / 14
The idea
Complexity
| Time | Space | Why |
|---|---|---|
O(V + E) | O(V + E) | Each node is dequeued once and each edge relaxed once. |
In Python
from collections import deque
def topo_order(n, edges):
adj = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges: adj[u].append(v); indeg[v] += 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 adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order if len(order) == n else [] # [] means a cycleSummary: say it in the interview
- Count each node's in-degree (unmet prerequisites). Start with the nodes at zero, run them, and decrement their dependents. A node joins the queue the moment it reaches zero. If some nodes never run, there is a cycle.
- Time O(V + E), space O(V + E). Each node is dequeued once and each edge relaxed once.