Free explainer · Video · Code · Quiz
Topological Sort (Kahn's Algorithm)
Put the tasks of a dependency graph in a valid order: repeatedly take what has no unfinished prerequisites, using in-degrees and a queue. Finds a cycle for free, and shows why many valid orders exist.
- Difficulty
- Medium
- Time
- O(V + E)
- Space
- O(V + E)
Try it yourself
Step through it at your own pace — this is Topological Sort Animation, running right on the page.
LiveTopological Sort Animation
Loading the preview…
How it works
The idea, a worked example, and the traps to avoid.
The idea
You can't take Algorithms before Data Structures, and you can't take Data Structures before Programming. A build tool can't link a program before it compiles every file it needs. Whenever things depend on each other, the question is the same: in what order can I do all of them?
Model it as a directed graph: each task is a vertex, and an edge u → v means "u must come before v". A topological order lists every vertex so that every edge points forward.
Kahn's algorithm builds that list one vertex at a time. The in-degree of a vertex is the number of edges pointing at it, which is the number of prerequisites still waiting. A vertex with in-degree 0 is ready: nothing holds it back. So:
- Count the in-degree of every vertex.
- Put every vertex with in-degree 0 in a queue.
- Take the front vertex and append it to the order. Cross out its outgoing edges: lower each neighbour's in-degree by 1. A neighbour that reaches 0 has just lost its last prerequisite, so it joins the queue.
- Repeat until the queue is empty.
Walkthrough
Six tasks, numbered 0 to 5, with edges 5→0, 5→2, 4→0, 4→1, 2→3 and 3→1. The in-degrees are [2, 2, 1, 1, 0, 0], so the queue starts with the two sources, in vertex order: 4, 5.
| Step | Take | What happens | Queue afterwards | Order so far |
|---|---|---|---|---|
| 1 | 4 | 4→0: in-degree of 0 drops 2 → 1. 4→1: in-degree of 1 drops 2 → 1 | 5 | 4 |
| 2 | 5 | 5→0: 1 → 0, so 0 is ready. 5→2: 1 → 0, so 2 is ready | 0, 2 | 4 5 |
| 3 | 0 | No outgoing edges | 2 | 4 5 0 |
| 4 | 2 | 2→3: 1 → 0, so 3 is ready | 3 | 4 5 0 2 |
| 5 | 3 | 3→1: 1 → 0, so 1 is ready | 1 | 4 5 0 2 3 |
| 6 | 1 | No outgoing edges | empty | 4 5 0 2 3 1 |
The order has 6 vertices, which is all of them, so it is valid: look at any edge, say 3→1, and 3 is indeed before 1.
Many orders are valid. In this graph there are 13. Kahn's algorithm gives one of them, and which one depends only on how you break ties. Here the rule is a plain first-in-first-out queue, seeded in vertex order, with neighbours visited in the order their list gives them. That way every language prints the same answer.
Cycles come for free
Suppose the graph has the edges 1→2, 2→3 and 3→1. Every vertex on that loop waits for another vertex of the loop, so none of them ever reaches in-degree 0. The queue runs dry while vertices are still missing from the order.
That is the whole cycle test: if the order is shorter than the number of vertices, a cycle exists and no valid order does. This listing returns null (None, an empty Optional, std::nullopt in the other languages). A self-loop u → u is the smallest cycle: u waits for itself, so it is never ready.
Note what the leftovers are: every vertex that never got placed, which includes vertices that are merely stuck behind a cycle. If you need the cycle itself, walk back through unplaced vertices from any of them, or use the DFS version below.
Complexity
Counting the in-degrees looks at each edge once. Every vertex enters the queue at most once and leaves once. Each edge is crossed out exactly once, when its start vertex is taken. That is O(V) + O(E) work in total.
Time: O(V + E). Space: O(V + E) for the graph, the in-degree array, the queue and the order.
The DFS alternative
You can also run a depth-first search, append each vertex to a list when it finishes (after all its descendants), and reverse the list at the end. On the walkthrough graph, starting the search from 0, 1, 2 … in turn gives the order 5 4 2 3 1 0. It is also O(V + E) and also correct, but it gives a different valid order. To detect a cycle, it needs a third state besides "unvisited" and "done": "on the current path". Meeting a vertex that is on the path means a cycle.
Kahn's is usually easier to explain and to step through, and it needs no recursion, so there is no stack overflow on a chain of a million tasks. DFS is handy when you are already running a DFS anyway.
Common bugs
- Counting in-degrees wrong. Increase
inDegree[v]for every edge u → v, once per edge. A repeated edge counts twice, and then it must also be crossed out twice. This listing does exactly that, so repeated edges are fine. - Forgetting to check the length. Without
order.length < graph.lengtha cyclic graph quietly returns a short, wrong "order". - Queueing a vertex twice. Push only when the in-degree becomes 0 (
=== 0), not whenever it is 0 or below. - Taking from the front of a JavaScript array with
shift(). It is O(n) on a big array. The listing keeps aheadindex instead. - Reading the order as "the" answer. There are usually many valid orders. If a test expects one exact order, it is really asking about the tie-breaking rule.
When to use it
Use it whenever tasks have prerequisites: course schedules, build and package dependencies, spreadsheet cell recalculation, task runners and CI pipelines, ordering database migrations. If the graph is not allowed to have a cycle, the same run is your validation: a null result means the dependencies contradict each other.
If you need the order to be the smallest in some sense (the alphabetically first valid order, or the highest-priority task first), swap the queue for a priority queue. If you need the longest chain of dependencies (the minimum number of rounds when independent tasks run in parallel), process the queue level by level.
Interview variations
- Course Schedule (can you finish all courses?). Build the graph from the prerequisite pairs and run Kahn's. The answer is
order.length === n. - Course Schedule II. The same run, but return the order itself, or an empty array when there is a cycle.
- Alien Dictionary. Compare neighbouring words to get letter-before-letter edges, then topologically sort the letters. A cycle (or a longer word placed before its own prefix) means the dictionary is invalid.
- Parallel courses (the minimum number of semesters). Take the whole queue as one semester, then the next queue as the next one. The number of rounds is the answer.
Code
The same algorithm, step for step, in 4 languages.
// Topological sort (Kahn's algorithm): line up the vertices of a directed graph so that every edge
// u → v has u before v. A vertex with no unfinished prerequisites (in-degree 0) is ready; take it,
// cross its edges out, and the vertices it was holding back may become ready in turn.
// If some vertices never become ready, they sit on a cycle and no valid order exists.
/**
* A valid order of the vertices, or null when the graph has a cycle.
*
* Deterministic: the queue starts with the ready vertices in vertex order, and each vertex's
* neighbours are visited in the order its list gives them, so every run (and language) agrees.
*
* @param {number[][]} graph adjacency list: graph[u] lists the vertices u points to
* (repeated entries are repeated edges; u itself in graph[u] is a self-loop, which is a cycle)
* @returns {number[] | null}
*/
export function topologicalSort(graph) {
const inDegree = new Array(graph.length).fill(0);
for (const neighbours of graph) {
for (const v of neighbours) inDegree[v]++;
}
const queue = [];
for (let u = 0; u < graph.length; u++) {
if (inDegree[u] === 0) queue.push(u);
}
const order = [];
let head = 0; // queue[head] is the front; entries before it are already taken
while (head < queue.length) {
const u = queue[head++];
order.push(u);
for (const v of graph[u]) {
inDegree[v]--;
if (inDegree[v] === 0) queue.push(v); // v's last prerequisite is done: it is ready
}
}
// A vertex on a cycle waits for another vertex of that cycle forever, so it never gets in.
if (order.length < graph.length) return null;
return order;
}
# Topological sort (Kahn's algorithm): line up the vertices of a directed graph so that every edge
# u -> v has u before v. A vertex with no unfinished prerequisites (in-degree 0) is ready; take it,
# cross its edges out, and the vertices it was holding back may become ready in turn.
# If some vertices never become ready, they sit on a cycle and no valid order exists.
from collections import deque
from typing import List, Optional
# Adjacency list: graph[u] lists the vertices u points to (repeated entries are repeated edges;
# u itself in graph[u] is a self-loop, which is a cycle).
Graph = List[List[int]]
def topological_sort(graph: Graph) -> Optional[List[int]]:
"""Return a valid order of the vertices, or None when the graph has a cycle.
Deterministic: the queue starts with the ready vertices in vertex order, and each vertex's
neighbours are visited in the order its list gives them, so every run (and language) agrees.
"""
in_degree = [0] * len(graph)
for neighbours in graph:
for v in neighbours:
in_degree[v] += 1
queue = deque(u for u in range(len(graph)) if in_degree[u] == 0)
order: List[int] = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0: # v's last prerequisite is done: it is ready
queue.append(v)
# A vertex on a cycle waits for another vertex of that cycle forever, so it never gets in.
if len(order) < len(graph):
return None
return order
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
/**
* Topological sort (Kahn's algorithm): line up the vertices of a directed graph so that every edge
* u → v has u before v. A vertex with no unfinished prerequisites (in-degree 0) is ready; take it,
* cross its edges out, and the vertices it was holding back may become ready in turn.
* If some vertices never become ready, they sit on a cycle and no valid order exists.
*/
public final class TopologicalSort {
private TopologicalSort() {
}
/**
* A valid order of the vertices, or an empty Optional when the graph has a cycle.
*
* <p>Deterministic: the queue starts with the ready vertices in vertex order, and each vertex's
* neighbours are visited in the order its list gives them, so every run (and language) agrees.
*
* @param graph adjacency list: graph.get(u) lists the vertices u points to (repeated entries
* are repeated edges; u itself in graph.get(u) is a self-loop, which is a cycle)
*/
public static Optional<List<Integer>> topologicalSort(List<List<Integer>> graph) {
int[] inDegree = new int[graph.size()];
for (List<Integer> neighbours : graph) {
for (int v : neighbours) {
inDegree[v]++;
}
}
Queue<Integer> queue = new ArrayDeque<>();
for (int u = 0; u < graph.size(); u++) {
if (inDegree[u] == 0) {
queue.add(u);
}
}
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int u = queue.remove();
order.add(u);
for (int v : graph.get(u)) {
inDegree[v]--;
if (inDegree[v] == 0) { // v's last prerequisite is done: it is ready
queue.add(v);
}
}
}
// A vertex on a cycle waits for another vertex of that cycle forever, so it never gets in.
if (order.size() < graph.size()) {
return Optional.empty();
}
return Optional.of(order);
}
}
// Topological sort (Kahn's algorithm): line up the vertices of a directed graph so that every edge
// u -> v has u before v. A vertex with no unfinished prerequisites (in-degree 0) is ready; take it,
// cross its edges out, and the vertices it was holding back may become ready in turn.
// If some vertices never become ready, they sit on a cycle and no valid order exists.
#include <cstddef>
#include <optional>
#include <queue>
#include <vector>
// Adjacency list: graph[u] lists the vertices u points to (repeated entries are repeated edges;
// u itself in graph[u] is a self-loop, which is a cycle).
using Graph = std::vector<std::vector<int>>;
// A valid order of the vertices, or std::nullopt when the graph has a cycle.
//
// Deterministic: the queue starts with the ready vertices in vertex order, and each vertex's
// neighbours are visited in the order its list gives them, so every run (and language) agrees.
std::optional<std::vector<int>> topologicalSort(const Graph& graph) {
std::vector<int> inDegree(graph.size(), 0);
for (const std::vector<int>& neighbours : graph) {
for (int v : neighbours) {
++inDegree[v];
}
}
std::queue<int> queue;
for (std::size_t u = 0; u < graph.size(); ++u) {
if (inDegree[u] == 0) {
queue.push(static_cast<int>(u));
}
}
std::vector<int> order;
while (!queue.empty()) {
int u = queue.front();
queue.pop();
order.push_back(u);
for (int v : graph[u]) {
--inDegree[v];
if (inDegree[v] == 0) { // v's last prerequisite is done: it is ready
queue.push(v);
}
}
}
// A vertex on a cycle waits for another vertex of that cycle forever, so it never gets in.
if (order.size() < graph.size()) {
return std::nullopt;
}
return order;
}
Test yourself
10 quick questions to check it stuck.
Q1 · Six tasks, numbered 0 to 5, with the edges (from → to) 5→0, 5→2, 4→0, 4→1, 2→3 and 3→1. What does topologicalSort(graph) return?
Take it further
- Animation
Topological Sort Animation
A glowing dependency graph that peels itself in order: Kahn's algorithm with live in-degree badges, a visible FIFO queue and the order filling up
Free
