Sub topic 7
Detecting Cycles While Sorting
A topological sort only succeeds on a directed acyclic graph. Real dependency data often contains mistakes: one package requires another that requires the first, or a build rule lists its own output as an input. A useful sort has to notice this. It should also tell the user which nodes form the loop, because "graph has a cycle" alone gives them nothing to fix.
This chapter assumes you have read the chapters on Kahn's algorithm and the DFS-based sort. It also assumes you can read Python that uses deque, recursion, and exceptions. Both earlier implementations already raise an error on a cycle. Here we look at why those checks work, how to turn them into a report that names an actual cycle, and which mistakes cause cycles to be missed or reported when none exist.
What Each Algorithm Sees When a Cycle Exists
The two algorithms find cycles in different ways.
| Algorithm | Signal | When it fires | What you know at that moment |
|---|---|---|---|
| Kahn's | Some nodes are never removed | After the queue empties | The set of stuck nodes, which holds every cycle plus everything downstream of a cycle |
| DFS | An edge leads to a GRAY node | During the search, at the first back edge found | One concrete cycle, sitting on the recursion stack |
Kahn's algorithm: nodes that never reach in-degree zero
A node joins the queue only when all of its predecessors have been removed. Take any node on a cycle. One of its predecessors is the previous node on the same cycle, and that node is waiting for its own predecessor on the cycle, and so on around the loop. No node in the cycle can go first, so none of them ever reaches in-degree zero. The queue runs dry, and len(order) ends up smaller than the number of nodes.
The stuck set is larger than the cycle. Every node reachable from a cycle stays stuck too, because it has a predecessor that never got removed.
DFS: an edge back to a node still in progress
In the three-color DFS, GRAY means the node has been entered but not finished, so it is somewhere on the current recursion stack. An edge u -> v where v is GRAY means v can reach u (that is how the search got from v to u), and now u reaches v. That closes a directed cycle. This kind of edge is called a back edge. A directed graph has a cycle exactly when a DFS finds a back edge.
Reporting an Actual Cycle
Extracting a cycle after Kahn's algorithm
Every stuck node has at least one stuck predecessor. If all its predecessors had been removed, its in-degree would have reached zero. So you can start at any stuck node and keep stepping to a stuck predecessor. With a finite number of nodes, you must eventually revisit a node, and the part of the walk from that node onward is a cycle. Because you walked backward along edges, reverse that part to get the forward direction.
from collections import deque
def kahn_with_cycle(graph):
"""Return (order, cycle). cycle is None if the graph is a DAG."""
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
queue = deque(u for u, d in indegree.items() if d == 0)
order, removed = [], set()
while queue:
u = queue.popleft()
order.append(u)
removed.add(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) == len(indegree):
return order, None
# Build predecessor lists restricted to stuck nodes.
stuck = [u for u in indegree if u not in removed]
stuck_set = set(stuck)
preds = {u: [] for u in stuck}
for u in graph:
if u in stuck_set:
for v in graph[u]:
if v in stuck_set:
preds[v].append(u)
# Walk backward until a node repeats.
position, path = {}, []
node = stuck[0]
while node not in position:
position[node] = len(path)
path.append(node)
node = preds[node][0]
cycle = path[position[node]:]
cycle.reverse()
return order, cycle
graph = {"x": ["a"], "a": ["b"], "b": ["c"], "c": ["a", "d"], "d": []}
order, cycle = kahn_with_cycle(graph)
print(order)
print(" -> ".join(cycle + cycle[:1]))
# ['x']
# b -> c -> a -> bThe walk starts at a, steps back to c, then to b, then reaches a again. Reversed, that gives b -> c -> a, and each of those edges exists in the graph. Node d never shows up in the report even though it is stuck. The extra work is O(V + E), so the total running time stays linear.
Recording the path during DFS
In the DFS version, the cycle is already on the stack when the back edge appears. Keep an explicit path list alongside the colors. When you hit a GRAY node v, the cycle is the part of path from v to the end.
class CycleFound(ValueError):
def __init__(self, cycle):
self.cycle = cycle
text = " -> ".join(map(str, cycle + cycle[:1]))
super().__init__(f"graph has a cycle: {text}")
def topo_sort_dfs_report(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color, order, path = {}, [], []
def visit(u):
color[u] = GRAY
path.append(u)
for v in graph.get(u, []):
c = color.get(v, WHITE)
if c == GRAY:
raise CycleFound(path[path.index(v):])
if c == WHITE:
visit(v)
path.pop()
color[u] = BLACK
order.append(u)
for u in graph:
if color.get(u, WHITE) == WHITE:
visit(u)
order.reverse()
return order
try:
topo_sort_dfs_report({"x": ["a"], "a": ["b"], "b": ["c"], "c": ["a", "d"], "d": []})
except CycleFound as err:
print(err)
print(err.cycle)
# graph has a cycle: a -> b -> c -> a
# ['a', 'b', 'c']Subclassing ValueError keeps this compatible with callers that already catch ValueError. Callers that want the nodes can read err.cycle instead of parsing the message. path.index(v) is a linear scan, but it runs at most once, just before the function exits.
Common Errors
Treating BLACK as a cycle
A frequent bug replaces the three colors with one visited set and reports a cycle whenever an edge reaches a visited node. That breaks on a diamond:
def broken_has_cycle(graph):
visited = set()
def visit(u):
visited.add(u)
for v in graph.get(u, []):
if v in visited:
return True # wrong: v may be finished, not in progress
if visit(v):
return True
return False
return any(visit(u) for u in graph if u not in visited)
diamond = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(broken_has_cycle(diamond)) # True, but the graph is acyclic
print(topo_sort_dfs_report(diamond)) # ['a', 'c', 'b', 'd']When the search reaches d the second time, through c, node d is already BLACK. It is finished, and no path leads from d back to c. Only GRAY means "still on the stack." The single-set trick works for undirected graphs, which is probably why it gets copied into directed code by mistake.
Counting the wrong number of nodes
Kahn's check compares len(order) against the total number of nodes. If some nodes appear only as edge targets and never as dictionary keys, len(graph) undercounts them:
graph = {"a": ["b"]} # "b" is not a key
# Wrong check: len(order) == 2, len(graph) == 1, reports a false cycle.
# Right check: compare against len(indegree), which includes "b".The reverse mistake also happens. Code that builds indegree only from keys crashes with KeyError on "b", or skips it entirely. Always build the node set from both the keys and the edge targets.
Self-loops and parallel edges
A self-loop a -> a is a cycle of length one. Both implementations above handle it: in Kahn's algorithm, a keeps in-degree 1 and preds["a"] == ["a"]. In the DFS, a is GRAY when it examines its own edge. Parallel edges such as ["b", "b"] add 2 to the in-degree and subtract 2 as they are processed, so they cause no false alarms. Don't remove duplicates from one structure but not the other, or the counts will disagree.
Recursion Depth
The recursive DFS fails on a long chain before it ever gets a chance to detect a cycle. CPython's default recursion limit is about 1000 frames, so a dependency chain of 10,000 steps raises RecursionError. Raising the limit with sys.setrecursionlimit only moves the problem, and very deep recursion can crash the interpreter. An explicit stack of (node, iterator) pairs keeps the same GRAY/BLACK logic without using recursion:
def topo_sort_dfs_iter(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color, order = {}, []
for root in graph:
if color.get(root, WHITE) != WHITE:
continue
color[root] = GRAY
stack = [(root, iter(graph.get(root, [])))]
while stack:
u, it = stack[-1]
for v in it:
c = color.get(v, WHITE)
if c == GRAY:
path = [n for n, _ in stack]
raise CycleFound(path[path.index(v):])
if c == WHITE:
color[v] = GRAY
stack.append((v, iter(graph.get(v, []))))
break
else:
stack.pop()
color[u] = BLACK
order.append(u)
order.reverse()
return order
chain = {i: [i + 1] for i in range(100_000)}
chain[100_000] = []
print(len(topo_sort_dfs_iter(chain))) # 100001
chain[100_000] = [50_000]
try:
topo_sort_dfs_iter(chain)
except CycleFound as err:
print(len(err.cycle)) # 50001The for ... else construct does the bookkeeping. If the loop breaks, the node has just pushed a child, and the outer while resumes with that child. If the iterator runs out without a break, every edge has been checked and the node is finished. Because each stack entry keeps its own iterator, the search picks up at the next unexplored edge when it returns to a node.
Exercises
Exercise
Run kahnwithcycle on {"p": ["q"], "q": ["r"], "r": ["q", "s"], "s": []}. Which nodes are stuck, and which cycle is reported?
Show answer
Only p is removed. q, r, and s are stuck; s is stuck only because it depends on r. The walk starts at q, steps to its stuck predecessor r, then back to q, so the reported cycle is q -> r -> q (printed as "q -> r -> q").
Exercise
In a DFS on a directed graph, the search examines an edge u -> v and finds v is BLACK. Explain why this edge cannot close a cycle.
Show answer
BLACK means every node reachable from v was fully explored before v finished. If a path from v to u existed, u would have been discovered and finished during v's search, so u would also be BLACK. But u is currently GRAY, so no path from v to u exists, and the edge u -> v cannot be part of a cycle.
Exercise
A teammate checks for cycles in Kahn's algorithm with "if len(order) != len(graph)". Give a three-node acyclic graph where this falsely reports a cycle, and state the fix.
Show answer
Example: {"a": ["b", "c"]}, where b and c appear only as targets. The order is ['a', 'b', 'c'] with length 3, but len(graph) is 1. The fix is to compare against the full node set, such as len(indegree), where indegree was built from both the keys and every edge target.