Data Structures · Visualization

Graph: Cycle Detection (DFS)

Graph

A cycle exists in a graph if you can start at a node, follow edges, and return to that same node without repeating an edge. Time: O(V + E). Space: O(V) for tracking state and the recursion stack.

Big-O: BFS/DFS visit each vertex and edge once: O(V + E).

Graph: Cycle Detection (DFS)

Graph

A cycle exists in a graph if you can start at a node, follow edges, and return to that same node without repeating an edge. DFS detects cycles by tracking not just 'visited' nodes but also nodes currently 'in progress' along the current path; if DFS ever reaches a neighbor that is still in progress on the current path, a cycle has been found. (For undirected graphs, a simpler check is: encountering a visited neighbor that isn't the immediate parent.)

How Cycle Detection (DFS) Works

  1. Start DFS from a node, marking it as 'in progress' (on the current path).
  2. For each neighbor, if it's already 'in progress', a cycle is found.
  3. If the neighbor is unvisited, recursively DFS into it.
  4. Once all of a node's neighbors are explored, mark it as fully 'done' (no longer in progress).

Cycle Detection (DFS) Worked Example

Input: Directed graph with edges A->B, B->C, C->A

  1. DFS from A: mark A in-progress, go to B
  2. Mark B in-progress, go to C
  3. Mark C in-progress, go to A
  4. A is already 'in progress' → cycle detected!

Output: true (a cycle exists: A -> B -> C -> A)

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
def has_cycle(graph):
    state = {}               # 0 = visiting, 1 = done
    def dfs(v):
        state[v] = 0
        for nxt in graph.get(v, []):
            if nxt in state:
                if state[nxt] == 0:
                    return True     # back edge
            elif dfs(nxt):
                return True
        state[v] = 1
        return False
    for v in graph:
        if v not in state and dfs(v):
            return True
    return False
# example: detect cycle
Input: Directed graph with edges A->B, B->C, C->A

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Cycle Detection (DFS) Time & Space Complexity

TimeO(V + E)
SpaceO(V) for tracking state and the recursion stack

When to Use Cycle Detection (DFS)

  • Detecting circular dependencies in build systems or package managers
  • Deadlock detection in operating systems (resource allocation graphs)
  • Validating that a workflow or task graph has no circular requirements

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.