Patterns

TS · Pattern 15

Topological Sort

Order nodes in a DAG such that every directed edge goes from earlier to later. Use BFS (Kahn's algorithm) with in-degree tracking or DFS with a finish-time stack.

Topological Sort
Time
O(V + E)
Space
O(V + E)

Spot it when

  • Task scheduling with prerequisites
  • Course prerequisites / build order
  • Detect cycles in directed graph