Skip to content

Topological Sort

Order the tasks so every dependency comes before the thing that needs it

1. Dependencies

A directed edge u → v means u must happen before v. A topological order is a linear ordering of the vertices that respects every edge. It exists if and only if the graph is a directed acyclic graph (DAG). If there is a cycle, the dependencies contradict each other and no order exists.

Build systems, course prerequisites, package managers, spreadsheet formulas, and task schedulers all need this ordering. The graph does not have to be connected; a forest of components is fine.

The order condition

2. Kahn's algorithm

Kahn's algorithm starts with the vertices that have indegree zero: nothing needs to happen before them. Remove one, append it to the order, and decrement the indegree of its outgoing neighbours. Any neighbour that reaches zero joins the frontier. If the order ends up shorter than the vertex count, the remaining vertices form a cycle.

Kahn's algorithm
queue = [v for v in vertices if indegree[v] == 0]
order = []
while queue not empty:
  u = queue.pop()
  order.append(u)
  for v in adjacency[u]:
    indegree[v] -= 1
    if indegree[v] == 0:
      queue.append(v)
return order if len(order) == len(vertices) else cycle

Example: 0→1, 0→2, 1→3, 2→3

Indegrees: 0 has 0, 1 has 1, 2 has 1, 3 has 2. Start with 0. Remove it, decrement 1 and 2 to zero. The frontier becomes 1 and 2. Remove both, decrement 3 twice to zero. Finally remove 3.

One valid order is 0, 1, 2, 3; another is 0, 2, 1, 3.

3. DFS order

The other standard method runs DFS and appends a vertex after all of its descendants have finished, then reverses the finishing order. The reversal is the topological order. This is the same depth-first traversal from the graph lesson, with a postorder list.

DFS finishing order
visited = set()
order = []
def dfs(u):
  visited.add(u)
  for v in adjacency[u]:
    if v not in visited: dfs(v)
  order.append(u)
for u in vertices:
  if u not in visited: dfs(u)
return reversed(order)

Kahn's algorithm is usually easier to explain and detects cycles naturally. DFS finishing order is convenient when you are already traversing the graph for another reason.

4. Cycle detection

In Kahn's algorithm, a cycle leaves at least one vertex with a positive indegree because every vertex in the cycle waits for another member of the cycle. In DFS, a back edge to a vertex on the recursion stack signals a cycle. Both tests are O(V+E).

Stable order

Many topological orders can be valid. If you need a deterministic one, use a priority queue instead of a plain queue for the zero-indegree frontier, or sort the adjacency lists. The order is a choice, not a property of the graph.

5. Applications

  • Build systems — compile a dependency before the target that imports it.
  • Course prerequisites — plan a semester without violating prerequisites.
  • Package managers — install dependencies bottom-up; report cycles.
  • Spreadsheet formulas — recalculate cells in dependency order.
  • Task scheduling — order jobs that share resources.

6. Practice

Try it

Why does a topological order require a DAG?

Try it

What does a nonzero leftover indegree mean after Kahn's algorithm?

Try it

Are topological orders unique?

Try it

How would you produce the lexicographically smallest topological order?

7. Resources

The graph lesson covers BFS and DFS; this lesson reuses the same adjacency-list model but cares about direction and indegree. The next lesson adds weights to the edges.

Next: weighted graphs & Dijkstra →

Continue the track

Site soundtrack