Topological Sort and Cycle Detection: Kahn's Algorithm and DFS
Suppose a list of courses has prerequisites: data structures needs the intro course, algorithms needs both data structures and discrete math, and so on. In what order can a student take them? That question, put a set of tasks in an order that respects every "this before that" rule, is topological sorting. Build systems, spreadsheet recalculation, software installers and task schedulers all answer it.
This guide covers the two standard algorithms, Kahn's algorithm and the depth-first search method, shows how each one detects a cycle, and ends with cycle detection in undirected graphs. Examples use Python 3.10 or later and only the standard library.
The definition, and when an order exists
Model the tasks as a directed graph: one vertex per task, and an edge u to v meaning "u must come before v". A topological order is a listing of all vertices in which every edge points forward, from an earlier vertex to a later one.
Such an order exists only if the graph has no directed cycle. If a cycle u to v to w to u existed, u would have to come before w and also after it. A directed graph with no cycles is called a directed acyclic graph, or DAG, and every DAG has at least one topological order, usually many. So "topologically sort this graph" always comes with a second task: notice when the input is not a DAG and say so, instead of printing a wrong order.
The example
Both programs use the same graph, stored as an adjacency list that maps each course to the courses it unlocks:
- intro unlocks data-structures and discrete-math;
- discrete-math unlocks algorithms;
- data-structures unlocks algorithms and databases;
- algorithms unlocks compilers.
That is V = 6 vertices and E = 6 edges. To make a cycle, each program then adds one bad rule: compilers is a prerequisite of data-structures.
Kahn's algorithm
The in-degree of a vertex is the number of edges coming into it: here, the number of prerequisites a course has. A vertex with in-degree 0 has nothing left to wait for, so it can go first. Kahn's algorithm repeats that idea:
- Compute every vertex's in-degree.
- Put every vertex with in-degree 0 in a queue.
- Take a vertex from the queue, append it to the output, and "remove" its outgoing edges by lowering each neighbor's in-degree by one. Any neighbor that reaches 0 joins the queue.
- Stop when the queue is empty.
from collections import deque
# course -> courses that list it as a prerequisite
unlocks = {
"intro": ["data-structures", "discrete-math"],
"discrete-math": ["algorithms"],
"data-structures": ["algorithms", "databases"],
"algorithms": ["compilers"],
"databases": [],
"compilers": [],
}
def kahn(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] += 1
queue = deque(u for u in graph if indegree[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) < len(graph):
return None # some vertices never reached in-degree 0
return order
print(kahn(unlocks))
unlocks["compilers"] = ["data-structures"] # add a cycle
print(kahn(unlocks))
['intro', 'data-structures', 'discrete-math', 'databases', 'algorithms', 'compilers']
None
The first line is a valid order: intro comes before both of its dependents, algorithms comes after both of its prerequisites, and compilers is last.
How Kahn's algorithm detects a cycle
The vertices on a cycle each wait for another vertex on the same cycle, so none of them ever reaches in-degree 0 and none is ever output. If the output has fewer than V vertices when the queue runs dry, the graph has a cycle. After the bad rule is added, data-structures waits for compilers, which waits for algorithms, which waits for data-structures, and the function returns None. The vertices left with a positive in-degree are the ones on a cycle or downstream of one, which is a useful starting point for an error message.
The algorithm is named after A. B. Kahn, who described it in "Topological sorting of large networks" (Communications of the ACM, 1962).
The DFS method
Depth-first search gives a second, equally fast method. Run DFS from every unvisited vertex, and record each vertex at the moment it finishes, meaning after DFS has explored everything reachable from it. A vertex finishes only after all the vertices it points to have finished, so reversing the finishing order puts every vertex before the vertices it points to.
To detect cycles, give each vertex one of three colors:
- white: not visited yet;
- gray: in progress, meaning DFS has entered it and not yet finished it, so it is on the current path;
- black: finished.
An edge from the current vertex to a gray vertex is a back edge: it leads back to a vertex on the current path, so it closes a directed cycle. An edge to a black vertex is harmless; that vertex is already placed.
WHITE, GRAY, BLACK = 0, 1, 2 # unvisited, in progress, done
unlocks = {
"intro": ["data-structures", "discrete-math"],
"discrete-math": ["algorithms"],
"data-structures": ["algorithms", "databases"],
"algorithms": ["compilers"],
"databases": [],
"compilers": [],
}
def dfs_topo(graph):
color = {u: WHITE for u in graph}
finished = []
def visit(u):
color[u] = GRAY
for v in graph[u]:
if color[v] == GRAY:
raise ValueError(f"cycle: back edge {u} -> {v}")
if color[v] == WHITE:
visit(v)
color[u] = BLACK
finished.append(u) # u finishes after everything it unlocks
for u in graph:
if color[u] == WHITE:
visit(u)
return finished[::-1]
print(dfs_topo(unlocks))
unlocks["compilers"] = ["data-structures"]
try:
dfs_topo(unlocks)
except ValueError as err:
print(err)
['intro', 'discrete-math', 'data-structures', 'databases', 'algorithms', 'compilers']
cycle: back edge compilers -> data-structures
The DFS order differs from Kahn's (discrete-math comes before data-structures here), and both are correct. Check any order by testing every edge: the source must appear before the target. When the cycle is added, the search reports the exact edge that closes it.
Two colors are not enough. With only "visited" and "unvisited", reaching an already-visited vertex could mean a cycle, or simply a vertex reached earlier along a different branch (data-structures and discrete-math both lead to algorithms, which is not a cycle). The gray state separates the two cases.
The recursive version goes one call deeper per vertex on the current path, so on a long chain of dependencies it can hit Python's default recursion limit of 1000. For large graphs, use Kahn's algorithm or rewrite the DFS with an explicit stack.
Running time
Both methods are O(V + E) with an adjacency list. Kahn's algorithm computes in-degrees by scanning every edge once, then outputs each vertex once and lowers an in-degree once per edge. The DFS method visits each vertex once and examines each edge once. Both use O(V) extra space for the in-degrees or colors, the queue or the recursion stack, and the output. On an adjacency matrix, scanning neighbors costs O(V) per vertex, so both become O(V^2). The graph representations guide explains the difference.
Which one to use
- Kahn's algorithm is iterative, so it has no recursion depth problem. It processes tasks in "ready" order, which makes it natural for schedulers: a vertex joins the queue the moment its last prerequisite is done. Replacing the queue with a min-heap (
heapq) gives the alphabetically smallest order, at O(V log V + E). - The DFS method reports the edge that closes a cycle, which makes for clear error messages, and it fits naturally when you already run DFS for other reasons.
Cycle detection in an undirected graph
Topological order is defined for directed graphs only. In an undirected graph, the question is just whether any cycle exists, and the test is simpler: during a traversal, if you reach an already-seen vertex that is not the one you came from, there are two different routes to it, which means a cycle. The parent check is needed because every undirected edge appears in both adjacency lists, so walking straight back along it must not count. The version below assumes a simple graph (no repeated edges and no self-loops):
def has_cycle_undirected(graph):
seen = set()
for start in graph:
if start in seen:
continue
seen.add(start)
stack = [(start, None)]
while stack:
u, parent = stack.pop()
for v in graph[u]:
if v == parent:
continue
if v in seen:
return True
seen.add(v)
stack.append((v, u))
return False
path = {1: [2], 2: [1, 3], 3: [2]}
triangle = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
print(has_cycle_undirected(path), has_cycle_undirected(triangle))
False True
It is O(V + E) like the others. Union-find gives another way: add the edges one at a time and report a cycle when an edge joins two vertices that are already in the same component. That is exactly the check Kruskal's algorithm makes when it builds a minimum spanning tree.
Check yourself
- A graph has the edges a to b, b to c and a to c. List every topological order. (Only one: a, b, c.)
- Kahn's algorithm outputs 7 vertices of a 9-vertex graph. What do you know? (The graph has a directed cycle. The 2 vertices left out lie on a cycle or depend on one.)
- Why is an edge to a black vertex not a cycle? (It has finished, so it is not on the current path. If a path led from it back to the current vertex, the search would already have found that cycle while exploring it.)
Topological sort is built on the traversals in breadth-first and depth-first search; Kahn's algorithm is a cousin of BFS, and the finishing-order method is DFS with one extra list.