Algorithms Playbook
PatternTime O(V + E) · Space O(V + E)8 min read

Topological sort: ordering tasks with dependencies

Ordering the nodes of a directed graph so every prerequisite comes first, and detecting cycles at the same time. The engine behind build systems and "Course Schedule".

In short

In a directed acyclic graph (DAG) a topological order puts every node after its prerequisites. Kahn's algorithm: repeatedly take a node with in-degree 0, remove it, and lower its neighbours' in-degree. If you can't order all nodes, there is a cycle. Cost: O(V + E).

Kahn's algorithm in action

Edges read as "must come before". The number under each node is how many prerequisites are still pending. Run the cycle example to see how the algorithm gets stuck.

Topological sort (Kahn's algorithm)
Graph
Speed

queue (in-degree 0)

0A1B

topological order

0·
Ain: 0Bin: 0Cin: 2Din: 1Ein: 2Fin: 1
1def topo_sort(n, edges):
2 indeg = [0] * n; adj = [[] for _ in range(n)]
3 for a, b in edges:
4 adj[a].append(b); indeg[b] += 1
5 queue = deque(i for i in range(n) if indeg[i] == 0)
6 order = []
7 while queue:
8 node = queue.popleft()
9 order.append(node)
10 for nb in adj[node]:
11 indeg[nb] -= 1
12 if indeg[nb] == 0:
13 queue.append(nb)
14 return order if len(order) == n else []
Edges mean "must come before" (A → C: do A first). Count each node's in-degree: how many prerequisites are still pending.

Variables

tasks6
Step 1/15· Nodes done: 0
If the order contains fewer nodes than the graph, there is a cycle. This is exactly how "Course Schedule" is solved.

What to remember

  • Directed graph with no cycles is the precondition. A cycle (A needs B needs A) has no valid order.
  • Cycle detection for free: if the output has fewer nodes than the graph, a cycle exists.
  • Many valid orders: any node of in-degree 0 may go next; a problem may ask for any one, or the lexicographically smallest (use a min-heap instead of a queue).
  • DFS alternative: do a DFS and push each node *after* visiting all its descendants; the reverse of that list is a topological order. A back edge to a node on the current path means a cycle.
ProblemNodesEdge a → b
Course Schedule I / IICoursesa is a prerequisite of b
Build orderPackagesa must be built before b
Alien dictionaryLettersa comes before b in the alien alphabet

Key takeaways

  • 01Topological order = every node after its prerequisites; only DAGs have one.
  • 02Kahn: queue the in-degree-0 nodes, remove them, update neighbours.
  • 03Fewer ordered nodes than total means a cycle.
  • 04O(V + E) time and space.

Check your understanding

1 of 3

Which graphs have a topological order?

Related topics