Sub topic 14
Complexity and Choosing the Right Method
This chapter assumes you have read the earlier chapters on parent-edge DFS, union-find, three-color DFS, Kahn's algorithm, cycle reconstruction, iterative DFS, Floyd's algorithm, and strongly connected components. You should be comfortable with Big-O notation and the idea of amortized cost. Here we compare those methods side by side and turn the comparison into a way to pick one.
Most of the methods run in linear time, so asymptotic cost alone rarely settles the choice. These questions matter more:
- Is the graph directed or undirected?
- Do edges arrive all at once or one at a time?
- Do you need the cycle itself, or just a yes or no?
- How large and how deep can the graph get?
The Cost of Each Method
In the table, V is the number of vertices and E is the number of edges. "Extra space" means memory beyond the input edge list.
| Method | Graph type | Time | Extra space | Gives you |
|---|---|---|---|---|
| DFS with parent-edge tracking | Undirected | O(V + E) | O(V + E) for adjacency, O(V) for visited and stack | Yes/no, and the cycle with parent pointers |
| Union-find (path halving + union by size) | Undirected | O(E · α(V)) | O(V) | Yes/no, and the first edge that closes a cycle |
| Three-color DFS (recursive) | Directed | O(V + E) | O(V) colors, O(V) call stack | Yes/no, and the cycle with parent pointers |
| Three-color DFS (iterative) | Directed | O(V + E) | O(V) colors and explicit stack | Same, with no recursion limit |
| Kahn's algorithm | Directed | O(V + E) | O(V) in-degrees and queue | Yes/no, and a topological order when acyclic |
| Floyd's tortoise and hare | Functional (out-degree 1) | O(μ + λ) | O(1) | Cycle start μ and length λ |
| Tarjan or Kosaraju SCC | Directed | O(V + E) | O(V) | Every cyclic region at once |
The function α is the inverse Ackermann function. It is at most 4 for any input that fits in physical memory, so union-find with both optimizations is effectively linear. The union-find version in the earlier chapter used path halving without union by size. That version is still fast in practice, but its amortized bound is O(log V) per operation rather than O(α(V)). If you rely on the worst-case bound, add union by size or rank.
Where the constant factors hide
Big-O hides some costs that matter in real code:
- Building the adjacency list. DFS and Kahn's algorithm both need adjacency lists. If your input is an edge list, building them is a full O(V + E) pass that allocates many small Python lists. Union-find reads the edge list directly and needs only one integer array.
- Early exit. DFS returns as soon as it finds a back edge, so on a graph with a cycle near the start it may touch very little of the graph. Kahn's algorithm cannot stop early. It only knows a cycle exists after the queue empties and
removed < n. - Recursion overhead. A Python function call costs much more than a loop iteration. The recursive three-color DFS is also limited by
sys.getrecursionlimit(), which defaults to 1000.
Failure Modes That Decide the Choice
Some choices are wrong rather than slow. The most common ones are below.
Union-find on a directed graph
Union-find merges sets and ignores edge direction. For the edges 0 → 1, 0 → 2, 1 → 2, it reports a cycle, because 1 and 2 are already connected through 0 when the third edge arrives. The directed graph has no cycle. Union-find only answers questions about undirected connectivity.
Recursion depth on long chains
A dependency chain of 5,000 packages is an ordinary input, and it breaks recursive DFS in Python. The script below shows the failure and shows Kahn's algorithm handling the same graph.
from collections import deque
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_directed(adj):
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return True
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))
def has_cycle_kahn(adj):
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(u for u in range(n) if indegree[u] == 0)
removed = 0
while queue:
u = queue.popleft()
removed += 1
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return removed < n
n = 5000
chain = [[i + 1] for i in range(n - 1)] + [[]] # 0 -> 1 -> ... -> 4999
print("Kahn:", has_cycle_kahn(chain))
try:
print("Recursive DFS:", has_cycle_directed(chain))
except RecursionError:
print("Recursive DFS: RecursionError")Output:
Kahn: False
Recursive DFS: RecursionErrorRaising the recursion limit with sys.setrecursionlimit is a fragile fix. Each Python frame also uses C stack, and a deep enough recursion can crash the interpreter outright instead of raising a clean exception. If inputs can be deep, use the iterative DFS or Kahn's algorithm.
Rerunning DFS after every new edge
Suppose edges arrive one at a time and you must reject the first edge that would close a cycle, as Kruskal's minimum spanning tree algorithm does. Running a full DFS after each insertion costs O(V + E) per edge, which is O(E · (V + E)) in total. Union-find checks each edge as it arrives in near-constant time:
def first_cycle_edge(n, edge_stream):
parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, (u, v) in enumerate(edge_stream):
ru, rv = find(u), find(v)
if ru == rv:
return i
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
return -1
edges = [(0, 1), (2, 3), (1, 2), (4, 5), (3, 0), (5, 6)]
print(first_cycle_edge(7, edges)) # 4: edge (3, 0) closes 0-1-2-3-0Union-find has two limits. It cannot delete edges, and it does not tell you which vertices form the cycle. If you need either, you have to keep an adjacency structure alongside it.
The directed version of this problem, detecting cycles while edges are inserted, needs incremental topological ordering algorithms. Those are beyond this tutorial. For moderate sizes, a common shortcut is to check whether the new edge u → v creates a cycle by searching from v for u before inserting the edge.
Kahn's algorithm does not point at the cycle
When Kahn's algorithm finds a cycle, the vertices that were never removed include every vertex on a cycle and also every vertex reachable from one. Here is an example. In the graph 0 → 1 → 0, 1 → 2, vertex 2 is never removed, but it is not on the cycle. To report the actual cycle, run three-color DFS with parent pointers on the leftover vertices. To report every cyclic region, use SCCs.
Counting all cycles
Every method in the table finds one cycle or tests whether any cycle exists. Listing every simple cycle is a different problem. A graph can have exponentially many simple cycles, so no algorithm can list them in polynomial time. Johnson's algorithm runs in O((V + E)(c + 1)), where c is the number of cycles. Before trying to list all cycles, check whether an SCC decomposition answers the real question.
A Decision Procedure
Some notes on the branches:
- Functional graphs come first. A functional graph is one where every vertex has exactly one outgoing edge. Examples include linked lists, iterated hash functions, and the
nextpointers of a permutation. Floyd's algorithm works on the functionfitself, so it never builds an adjacency list. If you need to check every starting point in such a graph, a single coloring pass over all vertices is O(V) and is simpler than running Floyd's algorithm from each start. - Undirected static graphs. DFS with parent-edge tracking and union-find are both near-linear. Use DFS when you also want the cycle's vertices. Use union-find when you only have an edge list and want minimal memory.
- Directed graphs where you need the order. Build tools and package managers need an order, not just a yes or no. Kahn's algorithm produces the order and detects the cycle in the same pass. It also gives you a natural place to break ties: if you replace the queue with a min-heap, you get the lexicographically smallest topological order at O((V + E) log V) cost.
- Directed graphs where you must explain the failure. A user who sees "circular dependency detected" wants to see the loop. Use iterative three-color DFS and reconstruct the cycle.
Summary of Trade-offs
| If your situation is... | Prefer | Avoid |
|---|---|---|
| Undirected, edge stream, no deletions | Union-find | Rerunning DFS per edge |
| Undirected, need the cycle's vertices | Parent-edge DFS | Union-find alone |
| Directed, deep chains possible | Kahn or iterative DFS | Recursive DFS in Python |
| Directed, need an error message showing the loop | Iterative three-color DFS | Kahn's leftover set alone |
| Directed, need all cyclic regions | SCC algorithm | Repeated single-cycle searches |
| Out-degree 1, memory tight | Floyd | Visited sets or hash maps |
| Directed graph, any situation | Any directed method | Union-find, undirected DFS |
Exercise
You receive 10 million undirected edges as a stream from disk and must report the index of the first edge that creates a cycle. You cannot hold an adjacency list in memory, but an integer array of size V fits. Which method do you choose, and what is its total cost?
Show answer
Union-find with path compression or halving plus union by size. It needs only the parent and size arrays (O(V) memory), reads each edge once, and costs O(E · α(V)) in total, which is effectively linear. DFS would need the full adjacency list and a rerun per edge to find the first closing edge.
Exercise
A build tool uses Kahn's algorithm and finds that 12 of 400 targets were never removed. A developer asks which targets form the circular dependency. Why can't you just print the 12 targets, and what do you run next?
Show answer
The leftover set contains every vertex on a cycle plus every vertex reachable from a cycle, so some of the 12 may only depend on the cycle without being part of it. Run iterative three-color DFS with parent pointers starting from the leftover vertices to extract one actual cycle. Or compute SCCs on the leftover subgraph to list every cyclic group.
Exercise
A colleague detects cycles in a directed task graph with union-find because "it's faster than DFS." For the edges a→b, a→c, b→c, what does their code report, and why is it wrong?
Show answer
It reports a cycle when it processes b→c, because b and c are already in the same set through a. The directed graph is acyclic, since nothing leads back to a or b. Union-find ignores direction, so it only answers undirected questions. Use three-color DFS or Kahn's algorithm instead.