0

Topological Sort (Kahn)

Medium

Repeatedly take any node with no remaining prerequisites. If you cannot empty the graph, there is a cycle.

indegreeDAGcycle detection
TimeO(V + E)
SpaceO(V)
Inputdirected edges u-v (u must come before v)
0011213241
queue
0

Indegrees counted. Nodes 0 have no prerequisites.

1 / 12
compute indegree for every node
queue = all nodes with indegree 0
while queue:
u = queue.pop(); order.push(u)
for v in adj[u]: if --indegree[v] == 0: queue.push(v)
if order.length < V: there is a cycle
Why it matters

The produced order being shorter than the node count is exactly the cycle test.

Keyboard
space play← → stepr restartctrl K search

More in Graphs

Next visualiser
Union-Find (DSU)