3. Topological Sort
Topological Sort: A linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge (u โ v), vertex u appears before v in the ordering.
Key Requirement: Graph MUST be a DAG (no cycles). If cycle exists, topological sort is impossible.
Applications: Task scheduling, course prerequisites, build systems, dependency resolution.
๐ก Real-Life Analogy:
In a university, some courses have prerequisites: Math โ Physics โ Engineering. Topological sort gives a valid order to take courses so prerequisites are always done first.
Method 1: DFS-based (Recursive)
Steps:
1. For each unvisited vertex, call DFS
2. After fully exploring all descendants of a vertex, push it onto a stack
3. Pop all elements from stack โ gives topological order
Time: O(V + E) | Space: O(V)
Method 2: Kahn's Algorithm (BFS / In-degree based)
Steps:
1. Compute in-degree of all vertices
2. Enqueue all vertices with in-degree = 0
3. Dequeue vertex u, add to result, decrease in-degree of all neighbors
4. If neighbor's in-degree becomes 0, enqueue it
5. If result size < V โ cycle exists (no valid topological sort)
Time: O(V + E) | Space: O(V)
Solved Example
Q: Find topological sort for DAG: 5โ2, 5โ0, 4โ0, 4โ1, 2โ3, 3โ1
In-degrees: 0โ2, 1โ2, 2โ1, 3โ1, 4โ0, 5โ0
Kahn's Steps:
Queue = [4, 5] (in-degree 0)
Dequeue 4 โ result=[4], reduce in-degree of 0โ1, 1โ1; Queue=[5]
Dequeue 5 โ result=[4,5], reduce 2โ0, 0โ0; Queue=[2,0]
Dequeue 2 โ result=[4,5,2], reduce 3โ0; Queue=[0,3]
Dequeue 0 โ result=[4,5,2,0]; Queue=[3]
Dequeue 3 โ result=[4,5,2,0,3], reduce 1โ0; Queue=[1]
Dequeue 1 โ result=[4,5,2,0,3,1]
Topological Order: 4 โ 5 โ 2 โ 0 โ 3 โ 1
(Other valid orders also possible depending on tie-breaking)
๐ก Key Points:
โข Topological sort is NOT unique โ multiple valid orderings exist for most DAGs
โข If DFS-based: result is reverse of finish order โ reverse the stack
โข If Kahn's: result size โ V โ cycle detected โ no topological sort possible