Cycle Detection Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Cycle Detection runs in O(V+E) time and O(V) space, in Python as in every other language.
- ✓There is no dedicated cycle-detection function, but the stdlib graphlib module (3.9+) gives you one as a side effect: graphlib.TopologicalSorter(graph).static_order() raises graphlib.CycleError eagerly -- prepare() runs its own DFS-based cycle check up front, before any node is yielded, specifically so it can report the exact cyclic node list, rather than discovering the cycle mid-traversal the way a Kahn's-algorithm-style "ran out of zero-indegree nodes" failure would, and the exception's args[1] is the list of nodes that make up the cycle.
- ✓Reach for graphlib first if you also need the topological order, since hand-rolling a second implementation duplicates code the standard library already ships and tests.
- ✓The Python trap: Python's recursion limit defaults to 1000 (sys.getrecursionlimit()), so a straightforward recursive DFS raises RecursionError on any graph with a path, cyclic or not, longer than about 1000 nodes, which is exactly the kind of adversarial or auto-generated input a cycle detector is likely to be run against.
- ✓Both DFS variants are O(V+E), every node is colored once and every edge examined once, but the constant factor differs sharply: recursive DFS pays a full Python frame per call, while the iterative version pays a list append/pop per stack push/pop plus a small two-element list allocation per frame (mutable [node, index], not a tuple, since the next-child index gets mutated in place), which is cheaper per operation.
What Cycle Detection actually is
Cycle Detection in Python: what you actually reach for
Python implementation
from enum import Enum, auto
from collections import defaultdict
class State(Enum):
WHITE = auto() # unvisited
GRAY = auto() # on the current DFS path
BLACK = auto() # fully explored
def has_cycle(graph: dict[int, list[int]]) -> bool:
state: dict[int, State] = defaultdict(lambda: State.WHITE)
stack: list[list[int]] = [] # [node, next-child-index]: no recursion
for start in graph:
if state[start] != State.WHITE:
continue
stack.append([start, 0])
state[start] = State.GRAY
while stack:
node, i = stack[-1]
children = graph.get(node, [])
if i < len(children):
stack[-1][1] += 1
child = children[i]
if state[child] == State.GRAY:
return True # back edge => cycle
if state[child] == State.WHITE:
state[child] = State.GRAY
stack.append([child, 0])
else:
state[node] = State.BLACK
stack.pop()
return False
# graphlib gets you cycle detection for free, as a side effect of toposort:
import graphlib
try:
graphlib.TopologicalSorter({1: [2], 2: [3], 3: [1]}).static_order()
except graphlib.CycleError as e:
cyclic_nodes = e.args[1]Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Cycle Detection?
There is no dedicated cycle-detection function, but the stdlib graphlib module (3.9+) gives you one as a side effect: graphlib.TopologicalSorter(graph).static_order() raises graphlib.CycleError eagerly -- prepare() runs its own DFS-based cycle check up front, before any node is yielded, specifically so it can report the exact cyclic node list, rather than discovering the cycle mid-traversal the way a Kahn's-algorithm-style "ran out of zero-indegree nodes" failure would, and the exception's args[1] is the list of nodes that make up the cycle. For a hand-rolled version, collections.defaultdict(list) builds the adjacency list and a plain dict of enum values tracks the three DFS states.
What is the most common Python mistake when implementing Cycle Detection?
Python's recursion limit defaults to 1000 (sys.getrecursionlimit()), so a straightforward recursive DFS raises RecursionError on any graph with a path, cyclic or not, longer than about 1000 nodes, which is exactly the kind of adversarial or auto-generated input a cycle detector is likely to be run against. Raising the limit with sys.setrecursionlimit() does not really fix it: you are trading a catchable RecursionError for an uncatchable interpreter segfault when the much lower underlying C stack limit is hit instead, so the real fix is the iterative version, not a bigger number.
How does Cycle Detection actually perform in Python?
Both DFS variants are O(V+E), every node is colored once and every edge examined once, but the constant factor differs sharply: recursive DFS pays a full Python frame per call, while the iterative version pays a list append/pop per stack push/pop plus a small two-element list allocation per frame (mutable [node, index], not a tuple, since the next-child index gets mutated in place), which is cheaper per operation. graphlib.TopologicalSorter is itself pure Python (no C accelerator module backs it, unlike heapq or collections), and it does strictly more bookkeeping than a minimal cycle-only DFS -- per-node predecessor counts, a ready-node list, done-tracking for a full topological order it does not need just to detect a cycle -- so it is comparable to, and sometimes slower than, a hand-rolled DFS that only needs to detect a back edge and stop. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.