Data Structures & Algorithms (Graphs): Topological Sorting

April 18, 2026

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.

Valid Topological Orderings (Permutations)
Validate accountReadyFetch holdingsReadyFetch quoteReadyMarket statusReadyBuying power2 leftPosition limits3 leftLock symbol2 leftRisk check2 leftBuild order1 leftSubmit order2 leftConfirm fill1 left
Ready to trigger
Triggered
No task triggered yet
0 / 11 triggered

Topological Sorting helps determine a valid execution order for these tasks while respecting their dependencies.


Key Observations

  1. Process a node only when all its prerequisites have been completed.

  2. 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

Language
1public int[] topologicalSort(int V, List<List<Integer>> adj) {
2
3 // Step 1: Count prerequisites for each vertex.
4 // indegree[v] = number of incoming edges to v.
5 int[] indegree = new int[V];
6
7 for (int u = 0; u < V; u++) {
8 for (int v : adj.get(u)) {
9 indegree[v]++;
10 }
11 }
12
13 // Step 2: Seed the queue with ready vertices.
14 // A vertex is ready when it has no remaining prerequisites.
15 Queue<Integer> queue = new LinkedList<>();
16
17 for (int i = 0; i < V; i++) {
18 if (indegree[i] == 0) {
19 queue.offer(i);
20 }
21 }
22
23 // Step 3: Process ready vertices in BFS order.
24 // Each processed vertex can unlock its dependents.
25 int[] result = new int[V];
26 int index = 0;
27
28 while (!queue.isEmpty()) {
29
30 // u is safe to run: every prerequisite is already done.
31 int u = queue.poll();
32
33 // Append u to the topological order.
34 result[index++] = u;
35
36 // Satisfy one prerequisite for each neighbor of u.
37 for (int v : adj.get(u)) {
38
39 indegree[v]--;
40
41 // v becomes ready once all of its prerequisites are done.
42 if (indegree[v] == 0) {
43 queue.offer(v);
44 }
45 }
46 }
47
48 // Step 4: If fewer than V vertices were ordered, a cycle exists.
49 if (index != V) {
50 return new int[0];
51 }
52
53 return result;
54}
Validate account00Fetch holdings10Fetch quote20Market status30Buying power40Position limits50Lock symbol60Risk check70Build order80Submit order90Confirm fill100
setup

Allocate indegree[] for every order-execution task. Each starts with zero counted dependencies.

u –
v –
indegree[]0 means ready
00
10
20
30
40
50
60
70
80
90
100
Queueempty
–
result[]0 of 11
·
·
·
·
·
·
·
·
·
·
·
1 / 106

Time Complexity

  1. Calculate indegree of every vertex: The graph has V nodes and E edges, and traversal touches both sets sequentially. Hence, it takes O(V + E).

  2. Initialize the queue: We iterate through all vertices exactly once to identify vertices with indegree 0. This takes O(V).

  3. 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

  1. Indegree array: We maintain an array to store the indegree of every vertex. Since we have (V) vertices, the array requires O(V).

  2. Queue: In the worst case, all vertices can have an indegree of zero and be inserted into the queue. This takes O(V).

  3. 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

Language
1public int[] topologicalSort(int V, List<List<Integer>> adj) {
2
3 // Track which vertices have already been explored.
4 boolean[] visited = new boolean[V];
5 // Vertices are pushed after all dependents are explored.
6 Stack<Integer> stack = new Stack<>();
7
8 // Start a DFS from every unvisited vertex.
9 for (int i = 0; i < V; i++) {
10 if (!visited[i]) {
11 dfs(i, adj, visited, stack);
12 }
13 }
14
15 // Popping the stack reverses finishing times
16 // into a valid topological order.
17 int[] result = new int[V];
18 int index = 0;
19
20 while (!stack.isEmpty()) {
21 result[index++] = stack.pop();
22 }
23
24 return result;
25}
26
27private void dfs(
28 int u,
29 List<List<Integer>> adj,
30 boolean[] visited,
31 Stack<Integer> stack) {
32
33 // Mark u so we never start another DFS from it.
34 visited[u] = true;
35
36 // Recurse into every unvisited dependent of u.
37 for (int v : adj.get(u)) {
38 if (!visited[v]) {
39 dfs(v, adj, visited, stack);
40 }
41 }
42
43 // u finishes only after all dependents finish.
44 stack.push(u);
45}
Validate account0Fetch holdings1Fetch quote2Market status3Buying power4Position limits5Lock symbol6Risk check7Build order8Submit order9Confirm fill10
setup

Allocate visited[]. Every task starts unvisited.

u –
v –
visited[]0 of 11
0F
1F
2F
3F
4F
5F
6F
7F
8F
9F
10F
DFS pathempty
–
Stackempty
–
result[]0 of 11
·
·
·
·
·
·
·
·
·
·
·
1 / 78

Time Complexity

  1. Iterating through all vertices: We iterate through every vertex to ensure all disconnected components are explored. This takes O(V).
  2. DFS traversal: Every vertex is visited exactly once. This takes O(V).
  3. Exploring adjacent vertices: Every directed edge is explored exactly once through the adjacency lists. This takes O(E).
  4. Pushing vertices onto the stack: Every vertex is pushed exactly once. This takes O(V).
  5. 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).