DSA Notes
Master topological sort for DAGs using both Kahn\
What is Topological Sort?
A topological sort of a Directed Acyclic Graph (DAG) is a linear ordering of all vertices such that for every directed edge u→v, vertex u comes before v in the ordering. Think of it as scheduling tasks where some tasks depend on others — you need to find an order that respects all dependencies.
Critical requirement: Topological sort only works on DAGs. If the graph has a cycle, no valid ordering exists (you cannot satisfy circular dependencies).
Real-World Analogy
Consider getting dressed in the morning:
- Underwear must come before pants
- Pants must come before belt
- Shirt must come before belt
- Socks must come before shoes
- Pants must come before shoes
| Underwear | Pants → Belt |
| Shirt ------ | Belt Shoes |
| Pants ──────── | ┘ |
One valid topological order: Underwear, Pants, Shirt, Belt, Socks, Shoes Another valid order: Socks, Underwear, Pants, Shirt, Belt, Shoes
Multiple valid orderings can exist!
Approach 1: Kahn\'s Algorithm (BFS-based)
The idea: repeatedly remove vertices with no incoming edges (in-degree = 0).
Why It Works
A vertex with in-degree 0 has no prerequisites — it is safe to place first. After "removing" it, new vertices may become prerequisite-free. This greedy process produces a valid topological ordering.
Dry Run
| Graph: 5 | 0, 5→2, 4→0, 4→1, 2→3, 3→1 |
| In-degrees | 0:2, 1:2, 2:1, 3:1, 4:0, 5:0 |
| Queue | [4, 5] (in-degree 0) |
| Process 4: reduce in-degree of 0( | 1) and 1(→1). Queue: [5] |
| Process 5: reduce in-degree of 0( | 0) and 2(→0). Queue: [0, 2] |
| Process 0 | no outgoing. Queue: [2] |
| Process 2: reduce in-degree of 3( | 0). Queue: [3] |
| Process 3: reduce in-degree of 1( | 0). Queue: [1] |
| Process 1 | no outgoing. Queue: [] |
| Result | [4, 5, 0, 2, 3, 1] ✓ |
Approach 2: DFS-based Topological Sort
The idea: perform DFS, and add each vertex to the result AFTER all its descendants are processed (post-order). Then reverse the result.
Why It Works
In DFS, a vertex is finished only after all vertices reachable from it are finished. So if u→v exists, v finishes before u. Reversing the finish order gives us u before v — exactly what we need.
Python Implementation
C++ Implementation
Time and Space Complexity
- Time: O(V + E) for both approaches — each vertex and edge processed once
- Space: O(V) for in-degree array / visited set + O(V) for queue/stack
Cycle Detection as a Bonus
Both approaches naturally detect cycles:
- Kahn's: If result has fewer than V vertices, remaining vertices are in a cycle
- DFS: Use three-color marking (WHITE/GRAY/BLACK). If DFS encounters a GRAY vertex, a cycle exists.
Applications
- Build systems (Make, Gradle): Compile files in dependency order
- Course scheduling: Prerequisites must be completed before a course
- Package managers: Install dependencies before dependent packages
- Spreadsheet evaluation: Compute cells in dependency order
- Task scheduling: Order tasks respecting dependencies
- Compilation: Order function definitions before usage in single-pass compilers
Kahn\'s vs DFS Approach
| Feature | Kahn\'s (BFS) | DFS |
|---|---|---|
| Cycle detection | Count vertices in result | Gray vertex revisited |
| Lexicographic order | Easy (use min-heap instead of queue) | Harder |
| Implementation | Slightly more code | Simpler recursive |
| All topological orders | Possible with backtracking | Possible with backtracking |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Topological Sorting.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, topological, sorting
Related Data Structures & Algorithms Topics