GraphsAnimated
Kahn's Algorithm
Repeatedly remove nodes with no incoming edges.
Time
O(V + E)
Extra space
O(V)
Use it for
Topological sort with cycle detection.
How it works
- Count each node’s incoming edges (its "in-degree").
- Put every node with in-degree 0 in a queue: nothing needs to come before them.
- Take a node from the queue, add it to the order, and reduce the in-degree of everything it points to. Any that reach 0 join the queue.
- If the order contains every node, it is a valid topological order; otherwise there was a cycle.
Watch it run
Loading animation…