Sub topic 15
Where Cycle Detection Is Used
This chapter assumes you already know three-color DFS and Kahn's algorithm from earlier chapters. It looks at real systems that rely on cycle detection, which algorithm each one usually picks, and why.
Dependency Resolution
Package managers such as pip, npm, and apt model packages as vertices. A directed edge goes from a package to each package it needs. To install anything, the manager needs a topological order, where every dependency comes before the packages that use it. Such an order exists only when the graph has no directed cycle.
Kahn's algorithm fits this job well because it gives you the install order and the cycle check in one pass. Any vertex it never removes is part of a cycle, or depends on one. Users can act on that list.
from collections import deque
def build_order(deps):
targets = set(deps)
for reqs in deps.values():
targets.update(reqs)
indegree = {t: 0 for t in targets}
users = {t: [] for t in targets}
for t, reqs in deps.items():
for r in reqs:
users[r].append(t)
indegree[t] += 1
queue = deque(sorted(t for t in targets if indegree[t] == 0))
order = []
while queue:
t = queue.popleft()
order.append(t)
for u in users[t]:
indegree[u] -= 1
if indegree[u] == 0:
queue.append(u)
stuck = sorted(targets - set(order))
return order, stuck
print(build_order({"app": ["lib", "utils"], "lib": ["utils"], "utils": []}))
# (['utils', 'lib', 'app'], [])
print(build_order({"app": ["lib"], "lib": ["utils"], "utils": ["app"], "docs": []}))
# (['docs'], ['app', 'lib', 'utils'])Build Systems
Make, Bazel, and Gradle treat build targets as a dependency graph, just like package managers. They also need to explain errors well. When a build fails, a message such as "cycle: app → lib → utils → app" saves the developer far more time than "cannot order targets." For that reason, many build tools run DFS with cycle reconstruction instead of Kahn's algorithm. The same problem shows up with circular imports between modules, in Python and in TypeScript bundlers alike.
Deadlock Detection
Operating systems and databases build a wait-for graph. Each vertex is a thread or transaction. An edge A → B means A is waiting for a lock that B holds. If every resource has a single instance, a directed cycle in this graph means a deadlock. None of the waiting parties can ever move forward.
To break the deadlock, the database picks one transaction on the cycle as the victim and aborts it. In the diagram, T4 is blocked but is not part of the deadlock. Aborting T4 would fix nothing. This is why the system needs the actual cycle and not just a yes-or-no answer. Wait-for graphs change constantly, so some databases skip the periodic check. They check for a cycle only when a new wait edge is added, starting the search from that edge.
Other Uses
| Application | Graph | Typical method |
|---|---|---|
| Spreadsheet formulas | Cell → cells it references | DFS from the edited cell |
| Course prerequisites | Course → required course | Kahn's algorithm |
| Network loop prevention | Undirected links between switches | Spanning tree, which uses union-find-style logic |
| Kruskal's minimum spanning tree | Undirected weighted edges | Union-find, to reject edges that close a cycle |
| Linked-list corruption checks | Node → next node | Floyd's tortoise and hare |
| Mutual recursion analysis in compilers | Function → functions it calls | Strongly connected components |
The method follows from the graph type and how the graph is updated. Directed graphs that are built once suit Kahn's algorithm or DFS. Undirected graphs that receive edges one at a time suit union-find. Graphs where each vertex has exactly one outgoing edge suit Floyd's tortoise and hare.
Exercise
A spreadsheet has A1 = B1 + 1, B1 = C1 * 2, and C1 = 5. The user changes C1 to = A1 - 3. Which algorithm would you run, starting where, and what should the error message report?
Show answer
Run a directed DFS (three-color, with parent pointers) starting from C1, the edited cell, following edges from each cell to the cells it references. The path C1 → A1 → B1 → C1 reaches C1 again while C1 is still gray. That is a back edge. Reconstruct the path and report "Circular reference: C1 → A1 → B1 → C1". Starting from the edited cell is enough, because any new cycle has to pass through the cell whose references just changed.
Exercise
In a wait-for graph, why does a cycle mean deadlock only when each resource has a single instance?
Show answer
If a resource has several instances, a waiting thread can still be served when any one holder releases an instance, even if the other holders are themselves waiting. A cycle then shows that a deadlock is possible, not that it has happened. Detecting deadlock with multi-instance resources needs a resource-allocation check, such as the detection variant of the banker's algorithm.