Topological Sort

Orders tasks so dependencies come first. Powers build systems, course prerequisites, and spreadsheet recalculation. Kahn: repeatedly remove nodes with indegree 0.

Method

• Compute indegree of each node. • Queue nodes with 0 indegree. • Remove, reduce neighbours' indegree. • Repeat.

Limitations

Fails (cycle) if no valid order exists. A topological order exists exactly for directed acyclic graphs. Detect cycles before using reverse DFS postorder or Kahn’s method as a valid ordering.

Example

Tasks: A before B,C; B before D -> order A,B,C,D or A,C,B,D.

Editorial clarification

A topological order exists exactly for directed acyclic graphs. Detect cycles before using reverse DFS postorder or Kahn’s method as a valid ordering.

Sources

Educational reference only, not professional advice.

All algorithms