Topological Sort (Kahn)
Directed graph • Indegree • BFS layer • len(order) < n ⇒ cycle
adj[u] lists vertices v with a directed edge u → v (finish u before v). Count indegrees, enqueue all zeros, repeatedly pop, append to order, relax outgoing edges. Same logic as vector<int> topoSort(int n, const vector<vector<int>>& adj) in C++.
TimeO(V+E)
SpaceO(V)
Step0/0
Indegree
Ready queue
Output order
Ready
Example: n = 4, edges 0→1, 0→2, 1→3, 2→3. Press Step to walk Kahn’s algorithm.