01. Topological sort
The problem can be found at the following link: Question Link
My Approach
To solve the problem efficiently, I have implemented the topological sort algorithm using a depth-first search (DFS) approach. Here's a breakdown of the steps involved:
Create a stack to store the sorted elements and initialize a vector to keep track of visited nodes.
Implement the DFS function, which takes in the number of nodes, an adjacency list, the visited vector, and the current node as parameters.
Mark the current node as visited.
Iterate through the adjacent nodes of the current node.
If an adjacent node has not been visited, recursively call the DFS function on that node.
Once all adjacent nodes have been visited, push the current node onto the stack.
In the topoSort function, initialize the visited vector with zeros.
Iterate through all nodes and call the DFS function on any unvisited nodes.
Pop the elements from the stack and store them in the visited vector in reverse order.
Finally, return the sorted vector.
Time and Auxiliary Space Complexity
Time Complexity:
O(V + E)
, whereV
represents the number of vertices (nodes) andE
represents the number of edges in the graph. This complexity arises from traversing all nodes and their adjacent edges during the DFS traversal.Auxiliary Space Complexity:
O(V)
, where V represents the number of vertices. This complexity is due to the usage of the stack and the visited vector, both of which grow with the number of nodes in the graph.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated