Learn / Graphs

Topological sort

A topological order lists the vertices of a directed acyclic graph so that every edge goes from earlier to later. Kahn's algorithm repeatedly takes a vertex with no remaining incoming edges; if some vertices are never taken, there is a cycle. Taking the smallest ready vertex each time gives one fixed answer, which this guide uses.

How to recognise it

  • Tasks with prerequisites.
  • Order of letters or steps implied by examples.
  • Longest or shortest paths in a DAG, or the earliest finishing time of each job.

Kahn's algorithm

542031
Arrows go from a task to the tasks that need it first. One valid order is 4 5 0 2 3 1; the smallest-first order is 4 5 0 2 3 1 as well.
indegree[v] = number of edges into v
ready = vertices with indegree 0 (smallest first)
while ready: u = take smallest; output u
             for v in adj[u]: indegree[v] -= 1; if 0: add v to ready
cycle if fewer than n were output

Vertices, edges, adjacency lists and the other words used here are on the Structures page.

ProblemGraph
course scheduleedge prerequisite → course
alien dictionarythe first differing letters of neighbouring words
job timeseach job ends one step after its last prerequisite
longest / shortest path in a DAGrelax edges in topological order

Common mistakes

  • Reversing the edge direction for prerequisites.
  • Missing the "a word followed by its own prefix" case in the alien dictionary.

Problems

0 of 6 solved

Check yourself

In the pictured DAG, which vertices can go first?

If Kahn's algorithm outputs fewer than n vertices?

Why are DAG shortest paths O(V + E), even with negative weights?