Skip to content
StackDecode
GraphsAnimated

Topological Sorting

Order a DAG so every edge points forward.

Time

O(V + E)

Extra space

O(V)

Use it for

Build order, course prerequisites.

How it works

  1. A topological order lists every node before the nodes it points to (think: courses before the courses that need them). It exists only if there is no cycle.
  2. Run a depth-first search. When a node has no unvisited neighbours left, it is finished: push it onto a stack.
  3. The finishing order, reversed, is a valid topological order.
  4. O(V + E).

Watch it run

Loading animation…