π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++)
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