Documentation Index
Fetch the complete documentation index at: https://swe.aboneda.com/llms.txt
Use this file to discover all available pages before exploring further.
Topological Sort
A linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edgeu → v, vertex u comes before v.
Two Approaches
1. Kahn’s Algorithm (BFS-based)
Uses in-degree counting:- Compute in-degree for every node
- Add all nodes with in-degree 0 to a queue
- Process queue: for each node, reduce in-degree of neighbors
- If a neighbor’s in-degree becomes 0, add it to the queue
- If result contains all nodes → valid ordering; otherwise → cycle exists
2. DFS-based
Use post-order DFS and reverse the result:- Run DFS from each unvisited node
- After visiting all neighbors, add current node to stack
- Reverse the stack for topological order
Complexity
| Time | Space | |
|---|---|---|
| Kahn’s (BFS) | O(V + E) | O(V) |
| DFS-based | O(V + E) | O(V) |
Cycle Detection
- Kahn’s: if result has fewer than V nodes → cycle exists
- DFS: if you encounter a node in the current recursion stack → cycle exists
Classic Problems
- Course Schedule I & II
- Alien Dictionary
- Minimum Height Trees
- Parallel Courses
- Build Order (project dependencies)
- Sequence Reconstruction
When to Use
- Task scheduling with dependencies
- Build systems and compilation order
- Course prerequisite chains
- Any problem involving ordering with constraints on a DAG
