Home
DSA Visualizer
Data Structures
Cycle Detection
Cycle Detection Visualization
Cycle detection finds whether a graph contains a cycle, using depth-first search (DFS). It is essential for deadlock detection and validating dependencies. Step through it in the interactive Cycle Detection visualization below.
NEW ROOT
Still open (recursion stack)
Empty
Closed
Nothing closed yet
A has not been reached yet. Start a new DFS from it.
Next
Open A. It stays on the recursion stack until every edge out of it has been followed.
Edges
Intuition
Imagine walking in a maze. If you keep following a path and end up at a spot you've already visited on your current journey, you've found a loop!
Cycle Detection finds these loops. The method differs slightly for directed vs. undirected graphs.
Concept
- Directed Graph: A cycle exists if we revisit a node that is currently in the recursion stack (part of the current path).
- Undirected Graph: A cycle exists if we visit a node that has already been visited, and it is NOT the parent of the current node.
How Cycle Detection Works
- Start DFS from an unvisited node.
- Mark node as visited AND add to recursion stack.
- For each neighbor:
- If in recursion stack -> Cycle found!
- If not visited -> Recursive DFS.
- Remove from recursion stack when backtracking.
- Start DFS, keeping track of the
parentnode. - Mark node as visited.
- For each neighbor:
- If neighbor == parent -> Ignore (it's the edge we came from).
- If visited -> Cycle found!
- If not visited -> Recursive DFS.
Cycle Detection Visualization, Step by Step
Watch the visualization:
- Solid blue node: Currently being visited.
- Pale blue node with a blue outline: Still open: on the recursion stack (the current path).
- Green node: Closed: fully explored, no cycle found through it.
- Red node/edge: The cycle that was detected.
When to Use
Use Cycle Detection when:
- Checking for deadlocks in resource allocation systems.
- Validating dependencies (e.g., circular dependencies in packages).
- Verifying if a structure is a Tree (Trees have no cycles).
- Infinite recurrence checks.
When NOT to Use
- Shortest Path: It detects existence of a cycle, not path lengths.
How to Identify
Problems asking for "deadlock", "circular dependency", "infinite loop", or "valid tree" typically require cycle detection.
Practice it on interview problems
LeetCode problems solved with the Graphs (Topological Sort) pattern, each with a step-by-step visualizer:
All Graphs (Topological Sort) problemsApplying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
