Topological Sorting is a way of arranging tasks in a sequence such that every task is performed only after completing the tasks it depends on.
Example: Stock Trading Order Execution Workflow
Imagine a customer places an order to buy 100 shares of Reliance Industries.
Before executing the order, the stock trading platform needs to perform several tasks,
such as validating the customer, checking whether sufficient funds are available, verifying
stock details, and performing risk assessment.
Topological Sorting helps determine a valid execution order for these tasks while respecting their dependencies.
Key Observations
-
Process a node only when all its prerequisites have been completed.
-
Every time we process a node, we satisfy one dependency for its neighbouring nodes. Once a node has no remaining dependencies, it becomes eligible for processing.
BFS-Based Approach: Kahn's Algorithm
Kahn's algorithm uses the concept of indegree (number of incoming nodes to a vertex) to identify vertices that are ready to be processed.
It then uses BFS (Breadth-First Search) with a queue to process these vertices and identify other vertices that become ready as their dependencies are satisfied.
Implementation
Allocate indegree[] for every order-execution task. Each starts with zero counted dependencies.
Time Complexity
-
Calculate indegree of every vertex: The graph has
Vnodes andEedges, and traversal touches both sets sequentially. Hence, it takesO(V + E). -
Initialize the queue: We iterate through all vertices exactly once to identify vertices with indegree
0. This takesO(V). -
Perform BFS: Every vertex is added to the queue at most once and removed from the queue exactly once (if it gets processed). Whenever we process a vertex, we iterate through its adjacent vertices. Since we process every vertex at most once, every directed edge is visited exactly once. Therefore, it takes
O(V + E).
Combining all three operations, the overall time complexity is O(V + E).
Space Complexity
-
Indegree array: We maintain an array to store the indegree of every vertex. Since we have
(V)vertices, the array requiresO(V). -
Queue: In the worst case, all vertices can have an indegree of zero and be inserted into the queue. This takes
O(V). -
Result array: We maintain an array to store the topological ordering. Since every vertex appears exactly once, it takes
O(V).
Combining all three, the overall space complexity is O(V).
DFS-Based Approach
Use recursion to explore all unvisited neighbouring vertices of the current node. Once all its neighbours have been explored, push the current node onto a stack.
Finally, pop the elements from the stack to obtain the topological ordering.
Implementation
Allocate visited[]. Every task starts unvisited.
Time Complexity
- Iterating through all vertices: We iterate through every vertex to ensure all disconnected components are
explored. This takes
O(V). - DFS traversal: Every vertex is visited exactly once. This takes
O(V). - Exploring adjacent vertices: Every directed edge is explored exactly once through the adjacency lists.
This takes
O(E). - Pushing vertices onto the stack: Every vertex is pushed exactly once. This takes
O(V). - Constructing the result array: Every vertex is popped from the stack exactly once. This takes
O(V).
Combinining all operations, the overall time complexity is O(V+E).
Space Complexity
Let's break down the space requirements:
- Visited array: We maintain a boolean array to track whether each vertex has been visited. This takes
O(V). - Recursion stack: In the worst case, DFS can go as deep as
(V)vertices, resulting in(V)recursive calls. - Stack for topological ordering: Every vertex is pushed onto the stack exactly once. This takes
O(V). - Result array: We maintain a 1-D array to store the final topological ordering. This takes
O(V).
The overall time complexity is O(V).