Skip to content
StackDecode
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

  1. Count each node’s incoming edges (its "in-degree").
  2. Put every node with in-degree 0 in a queue: nothing needs to come before them.
  3. 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.
  4. If the order contains every node, it is a valid topological order; otherwise there was a cycle.

Watch it run

Loading animation…