What is Topological Sort?
Graph Algorithms·5 min·Python code
Topological sort lines up the nodes of a directed acyclic graph so every edge points forward. If A must happen before B, A comes first. Task dependencies follow this order, and it exists only when the graph has no cycle.
Topological Sort Order for Dependencies
Think of course prerequisites. You cannot take Algorithms before Data Structures. Look at everything with nothing left to wait for, take one course and cross it off the lists of courses waiting on it. Repeat.
That is the full idea. Every node keeps a count of what must come before it, called its indegree. Nodes at zero are ready, and finishing one lowers the count of its neighbours, which frees them.
Kahn's Algorithm With a Queue
Count the indegree of every node and put every node with indegree zero in a queue. Pop one, append it to the order and drop the indegree of its neighbours by one. When a neighbour reaches zero, push it.
When the queue empties, compare the order length with the node count. Short orders mean the leftover nodes sit in a cycle, waiting on one another forever, and no valid order exists. That check costs nothing, which makes Kahn's algorithm the standard way to detect a cycle in a directed graph.
Topological Sort With DFS
Depth-First Search gives a second route. Visit a node, recurse into its neighbours and push the node onto a stack once its subtree is finished. Reversing that stack gives a topological order, because every node lands after everything it points to.
Kahn's version reads like the problem, spots cycles in one line and avoids deep recursion. DFS versions are shorter and fit when you already traverse the graph for another reason. Practise both on CodeStory's graph practice problems.
Topological Sort Code Example in Python
from collections import deque
def topological_sort(n, edges): # nodes are 0..n-1, edges are (before, after)
graph = [[] for _ in range(n)]
in_degree = [0] * n
for a, b in edges:
graph[a].append(b) # a must come before b
in_degree[b] += 1
ready = deque(i for i in range(n) if in_degree[i] == 0)
order = []
while ready:
node = ready.popleft()
order.append(node)
for nxt in graph[node]:
in_degree[nxt] -= 1 # one dependency less
if in_degree[nxt] == 0:
ready.append(nxt)
return order if len(order) == n else [] # short means a cycle
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Topological Sort Time and Space Complexity
| Time | O(V + E) for Kahn's algorithm and for the DFS version |
|---|---|
| Space | O(V) for the indegree array and the queue, plus O(V + E) for the graph itself |
Most graphs have many valid orders. Many problems accept any of them, while some ask for a rule like the lexicographically smallest order, which needs a heap instead of a queue.
Watch Kahn's Algorithm Free Every Node
Seeing indegree counts drop to zero shows why a node becomes ready. Follow the queue on your own input, one step at a time.
When to Use Topological Sort
- You order tasks or builds, like compile units, migrations, CI steps and spreadsheet cells.
- You solve course schedule problems, meaning whether every course can be taken and in what order.
- You resolve dependencies between packages or modules.
- You detect a cycle in a directed graph as a byproduct of the same pass.
Mistakes to Avoid
- Using undirected graphs. Edges have no before and after there, so no topological order exists.
- Ignoring cycles. No order exists for a cyclic graph, and your code must say so instead of returning a partial list.
- Expecting one answer. Several orders are valid for most graphs.
- Using it for shortest paths. Choose BFS or Dijkstra, because a topological order only fixes the sequence.
Topological Sort FAQs
What is the time complexity of topological sort?
O(V + E). Every node enters the queue once and every edge gets checked once, in Kahn's algorithm and in the DFS version.
What happens if the graph has a cycle?
No topological order exists. In Kahn's algorithm the queue empties while nodes remain, so the result is shorter than the node count. That gap is how you detect the cycle.
Should I use Kahn's algorithm or the DFS version?
Kahn's algorithm reads like the problem and detects cycles with one comparison. DFS is shorter and natural when you already traverse the graph, but watch recursion depth on large graphs.
Is the topological order unique?
Rarely. Order is unique only when exactly one node has indegree zero at every step, which means the graph is a single chain.
What is indegree?
Indegree counts the edges that point into a node, or in other words the tasks that must finish before it. Nodes with indegree zero are ready to start.
Can topological sort work on an undirected graph?
No. Undirected edges have no before and after, so there is nothing to order.
How do I practise topological sort on CodeStory?
Watch indegree counts drop in the visualiser, write Kahn's loop yourself, then try CodeStory's graph practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code Kahn's algorithm yourself, then explain every indegree in a scored mock round.
Talk to a Mentor