Topological Sort (Kahn) visualization

Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.

A vertex with in-degree 0 has no unmet prerequisites, so it can go next. Removing it lowers its successors' in-degrees, possibly freeing them.

Edge case: if a cycle exists, its vertices never reach in-degree 0 — the output is shorter than V, which is exactly how Kahn's algorithm detects cycles.

Complexity

Time: best O(V + E), average O(V + E), worst O(V + E). Space: O(V). Difficulty: Intermediate.

Pseudocode

procedure topoSort(G):
  indeg[v] ← number of incoming edges
  queue ← every v with indeg[v] = 0
  while queue not empty:
    u ← dequeue; order.append(u)
    for each edge u → v:
      indeg[v] ← indeg[v] − 1
      if indeg[v] = 0: enqueue v
  if |order| < |V|: the graph has a cycle

More graphs algorithms