Trees and graphs · Intermediate

Topological ordering

Order tasks so every dependency comes first: repeatedly take a task with no unmet prerequisites, and if none is left early the graph has a cycle.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

A directed acyclic graph of dependencies has at least one node with no incoming edge. Kahn's algorithm puts all such nodes in a queue, outputs one, removes its outgoing edges (decrementing in-degrees), and enqueues any node whose in-degree drops to zero.

If the output has fewer nodes than the graph, the remaining nodes all lie on or behind a cycle, so no valid order exists. The DFS alternative outputs nodes in reverse post-order and detects cycles with a three-colour visited state.

How to recognise it

  • Prerequisites, build order, course schedule, task dependencies, compile order.
  • "Is it possible to finish all tasks?" (cycle detection in a directed graph).
  • Processing a DAG in dependency order, such as longest path in a DAG or DP over a DAG.

When not to use it

  • The graph is undirected: there is no direction to order by (use union-find or DFS for cycles).
  • You need a unique order but several nodes have in-degree zero at once; topological orders are generally not unique.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

indegree = {v: 0 for v in nodes}
for (u, v) in edges: indegree[v] += 1        # u must come before v
queue = deque(v for v in nodes if indegree[v] == 0)
order = []
while queue:
    u = queue.pop_front(); order.append(u)
    for v in out[u]:
        indegree[v] -= 1
        if indegree[v] == 0: queue.push_back(v)
if len(order) < len(nodes): report cycle
return order
  • Use a min-heap instead of the queue when the task asks for the lexicographically smallest valid order.

Complexity

Time O(V + E), extra space O(V + E). Every node enters the queue once and every edge decrements one in-degree once. Storing the adjacency list takes O(V + E).

Worked examples

Build order for parse → check → emit, with lex → parse

In-degrees: lex 0, parse 1, check 1, emit 1. Queue [lex]. Output lex; parse drops to 0. Output parse; check drops to 0. Output check, then emit. Order: lex, parse, check, emit.

Pitfalls

  • Reversing edge direction (u → v must mean "u before v" throughout).
  • Forgetting nodes that have no edges at all.
  • Not checking the output length, so a cycle silently produces a partial order.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.topological-ordering · version 1