πDay 6. Topological sort π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a Directed Acyclic Graph (DAG) with V vertices (numbered from 0 to V-1) and E directed edges (represented as a 2D list where each edge is given as [u, v] indicating an edge from u to v), return a topological ordering of the vertices.
A topological sort of a DAG is a linear ordering of vertices such that for every directed edge u -> v, vertex u appears before vertex v in the ordering. Note: Since there can be multiple valid topological orders, you may return any one of them. The returned ordering is considered correct if for every directed edge u -> v, u comes before v.
π Example Walkthrough:
Example 1:
Input:
V = 4, E = 3
edges = [[3, 0], [1, 0], [2, 0]]Output:
trueExplanation:
The output true denotes that the ordering is valid.
Few valid topological orders are:
[3, 2, 1, 0]
[1, 2, 3, 0]
[2, 3, 1, 0]
Example 2:
Input:
Output:
Explanation:
The output true denotes that the returned ordering is valid.
Few valid topological orders for this graph are:
[4, 5, 0, 1, 2, 3]
[5, 2, 4, 0, 1, 3]
Constraints:
2 β€ V β€ 10Β³
1 β€ E (edges.size()) β€ (V * (V - 1)) / 2
π― My Approach:
Kahnβs Algorithm (BFS-based Topological Sort)
Algorithm Steps:
Construct the Graph:
Build an adjacency list from the edge list.
Create an in-degree array to store the number of incoming edges for each vertex.
Initialize the Queue:
Push all vertices with in-degree 0 into a queue.
Process the Queue:
While the queue is not empty, pop a vertex and add it to the result list.
For each neighbor of the popped vertex, reduce its in-degree by 1.
If any neighbor's in-degree becomes 0, add it to the queue.
Final Check:
If the result list contains all vertices, the ordering is valid.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(V + E), as every vertex and edge is processed exactly once.Expected Auxiliary Space Complexity:
O(V + E), due to the storage required for the adjacency list, in-degree array, and queue.
π Solution Code
Code (C++)
β‘ Alternative Approaches
π 2οΈβ£ DFS-Based Topological Sort (Recursive)
Algorithm Steps:
Convert the list of edges into an adjacency list.
Use a
visitedarray to avoid re-visiting nodes.For each unvisited node, run a DFS traversal.
Once all neighbors are processed, add the node to the result stack.
Reverse the result for topological order.
π Complexity Analysis:
Time Complexity:
O(V + E)Space Complexity:
O(V + E)(Adjacency list + recursion stack)
β Why This Approach?
Itβs the classic and intuitive way to compute topological sort using depth-first traversal. Very concise and clean for problems without large recursion depth.
π 3οΈβ£ DFS (Iterative using Stack)
Algorithm Steps:
Convert the edge list to an adjacency list.
Instead of recursion, use an explicit stack to perform DFS.
Keep track of the index of each nodeβs current child to process.
Add nodes to the result only when all their children are done.
Reverse the result stack for final order.
π Complexity Analysis:
Time Complexity:
O(V + E)Space Complexity:
O(V + E)
β Why This Approach?
It simulates recursion using an explicit stack, which helps avoid recursion limits in large graphs and makes it suitable for iterative-only environments.
π Comparison of Approaches
Approach
β±οΈ Time Complexity
ποΈ Space Complexity
β Pros
β οΈ Cons
Kahnβs Algorithm (BFS)
π’ O(V + E)
π‘ O(V + E)
Iterative, detects cycles, queue-based
Less intuitive for some, more verbose
DFS (Recursive)
π’ O(V + E)
π‘ O(V + E)
Simple and elegant, classic topological sort
Stack overflow risk on large/deep graphs
DFS (Iterative using Stack)
π’ O(V + E)
π‘ O(V + E)
Avoids recursion limit
Slightly complex and harder to follow
β Best Choice?
Use DFS (Recursive) for simpler problems and shorter DAGs.
Use Kahnβs Algorithm when cycle detection or iterative logic is required.
Use Iterative DFS to avoid stack overflow in recursion-heavy cases.
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated