Topological sort lines up the vertices of a directed acyclic graph (DAG) in a topological order, where every edge points from an earlier vertex to a later one. Kahn's algorithm finds such an order with a queue of the vertices that have no incoming edges left, in O(V + E) time with an adjacency list and O(V²) with an adjacency matrix. This page explains how it works, with a step-by-step animation of Kahn's algorithm on two chains from the VisiGrab app.
// how topological sort works
A topological sort lines up the vertices of a directed graph in a topological order: every edge u → v puts u before v. Only a directed acyclic graph (DAG), a directed graph with no cycle, has one: around a cycle, each vertex would have to come before itself. Kahn's algorithm (A. B. Kahn, 1962) finds one with a queue of the vertices that have no incoming edges left. It takes O(V + E) time for V vertices and E edges.
An undirected graph with an edge has no topological order: that edge leads both ways, so it would put each end before the other.
The in-degree of a vertex is the number of edges pointing to it, one for each vertex that must come directly before it. During the sort it counts only those not yet placed, so a vertex whose in-degree is 0 can go next.
Kahn's algorithm keeps the ready vertices in a queue, first in, first out. To enqueue a vertex is to add it at the queue's rear; to dequeue is to remove the one at its front. So the vertex that became ready first is placed first.
1. Count in-degrees: start every vertex at 0, then read each edge once and add 1 to the in-degree of the vertex it points to.
2. Enqueue the sources: enqueue every vertex with in-degree 0, called a source.
3. Dequeue and decrement: dequeue the front vertex and append it to the order. Lower by 1 the in-degree of each of its out-neighbors, the vertices its edges point to, and enqueue any that reach 0. Repeat until the queue is empty.
The app's code returns the order and a cycle flag. In pseudocode, with its names:
for each vertex v in vertices
inDegree[v] = 0
adjacency[v] = empty list
for each edge (u, v) in edges
adjacency[u].add(v)
inDegree[v] = inDegree[v] + 1
queue = empty queue
for each vertex v in vertices
if inDegree[v] == 0
queue.enqueue(v)
result = empty list
while queue is not empty
u = queue.dequeue()
result.add(u)
for each v in adjacency[u]
inDegree[v] = inDegree[v] - 1
if inDegree[v] == 0
queue.enqueue(v)
hasCycle = size(result) != V
return result, hasCycle
The second loop reads each edge once, to build the adjacency list and count the in-degrees. Sources are enqueued in the order of vertices, which settles ties: A goes before E on the player's graph. If size(result) < V at the end, some vertices never reached 0, and hasCycle is true.
The player below runs Kahn's algorithm on the app's default graph, two separate chains, with the queue and the growing order beside it. The order comes out A, E, B, F, C, D, as the queue takes turns between the chains. At the end a dotted line joins the vertices in that order, not along edges: only its last segment, C to D, lies on an edge.
It is the list a topological sort produces: every vertex once, with each edge pointing from an earlier vertex to a later one, so every vertex comes after all the vertices it depends on. One graph can have several.
Yes. A DAG always has a source: following edges backwards from any vertex never meets a vertex twice, as that would be a cycle, so the walk ends at a vertex with no incoming edge. Placing that source and removing its edges leaves a smaller DAG, so Kahn's algorithm never runs out of ready vertices before the end.
No. Around a directed cycle, each vertex would have to come before itself, so no order exists. Kahn's algorithm then leaves the cycle's vertices unplaced, which is how it detects that there is one.
On a cycle, each vertex waits for the one before it, so none of them reaches in-degree 0. The queue runs empty with vertices still unplaced, and the order holds fewer vertices than the graph: that is how the app's code sets its cycle flag. The vertices left out lie on a cycle or after one. With A → B, B → A and B → C, C is left out too, though it is on no cycle. Kahn's algorithm shows that a cycle exists, not which one.
Not in general: whenever more than one vertex is ready, any of them may go next. The player's graph has 15 orders: E and F, in that order, take any 2 of the 6 places, and A, B, C and D fill the rest in order. An order is the only one exactly when each pair of consecutive vertices in it is joined by an edge. The player's dotted line fails that test.
The container that holds the ready vertices decides which order comes out. A stack, last in, first out, gives E, F, A, B, C, D. A min-heap, a priority queue that hands out the smallest label first, gives the lexicographically smallest order, A, B, C, D, E, F, in O(V log V + E) time.
Each vertex is enqueued and dequeued once, and each edge is read twice: once to count an in-degree, once to lower it. That is O(V + E) time with an adjacency list. With an adjacency matrix, finding a vertex's out-neighbors reads a whole row of V cells, so the sort takes O(V2), as in the app's Graph Constructor. Extra space is O(V) for the in-degrees, the queue and the order. Building the adjacency list from an edge list, as the pseudocode does, adds O(V + E).
Either: topological sort is the task, and Kahn's algorithm and the DFS-based method are two algorithms for it. Kahn's algorithm is often called topological sort by BFS, after its queue, and the app's card reads Topological Sort (BFS). It is not a breadth-first search, though: it has no start vertex and no visited marks, and a vertex joins the queue only once every vertex that points to it has been placed, not when it is first reached. On the player's graph a BFS from A never reaches E or F. Kahn's algorithm starts from both sources, so a disconnected graph needs nothing extra.
The DFS-based method reverses the order in which a depth-first search finishes the vertices, its postorder. A vertex finishes only after every vertex it leads to, so in reverse it comes before them all. The order in which DFS first visits the vertices does not work: with A → C and B → C, a DFS from A visits C before B, though B must come first.
Choose Kahn's algorithm for a loop without recursion, or for the vertices ready at each moment, as in parallel scheduling. Choose DFS to report the cycle itself, by its back edge; a recursive DFS can overflow the call stack on a long chain.
| Kahn's algorithm | DFS-based | |
|---|---|---|
| Player's graph | A, E, B, F, C, D | E, F, A, B, C, D (DFS from A, then E) |
| Time | O(V + E) | O(V + E) |
The app's code gives the same order and cycle flag in all three languages. Of their standard libraries, only Python's has a topological sort.
Note
graphlib.TopologicalSorter, in Python's standard library since 3.9, takes a dict that maps each vertex to its predecessors, not to its out-neighbors. A cycle raises CycleError, which carries one cycle.
Java and C++ need a library, such as JGraphT's TopologicalOrderIterator or the Boost Graph Library's topological_sort.
Note
Boost's topological_sort is DFS-based and writes the vertices in reverse topological order, so read its output from the end.
The full source code is on GitHub, in Python, Java and C++.
O(V + E), even with negative weights, which Dijkstra's algorithm cannot handle and Bellman-Ford handles more slowly.// in the app
In VisiGrab, Kahn's algorithm runs on four example graphs, with an in-degree beside each vertex, the queue, the growing order and a message for every step.
The Examples dialog shows four thumbnails and remembers your pick. Besides the two chains there are a diamond, a five-vertex graph where C and E each wait on two edges, and a six-vertex graph where F waits on three and counts down 3, 2, 1, 0.
In the Graph Constructor, pick Topo Sort, draw a directed graph of up to 12 vertices and tap Apply. Each tap on Next adds one vertex to the topological order, and from the second vertex on a line is drawn from the one before. If your graph has a cycle, the app says so and shows no order.
The info dialog has two tabs. Overview defines the order, shows why a cycle rules it out and why several orders can be valid, and names four applications; Algorithm gives Kahn's four steps with an in-degree picture, O(V + E), cycle detection and the DFS-based alternative.
Kahn's algorithm in each language returns the order together with a cycle flag. Four key points, from in-degree computation to cycle detection, explain it, with a link to the full source on GitHub.
Eight questions with an explanation for every option: what an ordering is, why a cycle rules it out, in-degree, what follows a dequeue, what a short order means, and why one graph can have several orders.
Breadth-First Search and Depth-First Search walk a graph from one start vertex, Dijkstra and Bellman-Ford find shortest paths, and Prim and Kruskal build minimum spanning trees.
// build your own
Download VisiGrab to watch in-degrees count down to 0 on four example graphs, then draw a directed graph of your own and sort it.
Topological sort is one of 30+ topics. See them all