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
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.
| Problem | Graph |
|---|---|
| course schedule | edge prerequisite → course |
| alien dictionary | the first differing letters of neighbouring words |
| job times | each job ends one step after its last prerequisite |
| longest / shortest path in a DAG | relax 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
- Topological sort or Kahn's algorithmmediumguide ready
- Course Schedulemediumguide ready
- Course Schedule IImediumguide ready
- Minimum time taken by each job to be completed given by a Directed Acyclic Graphmediumguide ready
- Longest path in a Directed Acyclic Graphmediumguide ready
- Alien Dictionaryhardguide ready