Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Cycle Detection Implementation in Python

14 min readintermediate
Website QA and SEO audits

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 asks whether a graph contains a path that returns to a node it already visited while that node is still "open", still an ancestor on the current traversal, not merely visited earlier at some point. For directed graphs the standard technique is a depth-first search that colors each node white (unvisited), gray (on the current path), or black (fully explored), and reports a cycle the instant an edge leads to a gray node; an edge to a black node is not a cycle, it is just a shared descendant reached by two different paths. Undirected graphs use a simpler rule, an edge into an already-visited node that is not the edge you just arrived on is a cycle, because in an undirected graph there is no way to be "still open" without being trivially adjacent to your own parent. What differs across the eight languages below is not the coloring rule; every one of them runs the same three-state DFS. What differs is how each language forces you to represent "the current path": as a real call stack you can silently overflow, as an explicit data structure you must build yourself, or as an ownership structure where an accidental graph cycle becomes a memory leak entirely distinct from the logical cycle the algorithm is looking for.

Cycle Detection in Python: what you actually reach for

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.

Python implementation

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. When you only need the boolean answer, write the DFS iteratively with an explicit stack of (node, next-child-index) frames rather than recursively, a reviewer will ask why you trust the input's depth if you recurse, because nothing in a graph function's signature bounds how deep the caller's data actually goes.
python
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 Free

The Python-specific 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. 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.

Performance in Python, beyond the O(V+E)

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. The asymptotic cost is the same in every language, O(V+E) time and O(V) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Cycle Detection between languages.

Real-World Applications

Cycle Detection applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Cycle Detection helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Cycle Detection appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Cycle Detection over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Cycle Detection to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.