Cycle Detection Implementation in Java
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 Java as in every other language.
- ✓java.util.HashMap for adjacency and state, java.util.ArrayDeque as an explicit stack for the iterative version, and java.util.BitSet as a real, allocation-light alternative to two HashSet<Integer> instances (or two boolean[] arrays) when node IDs are dense, BitSet stores one bit per node instead of boxing every ID into an Integer.
- ✓Model the three states with a real enum (enum State { WHITE, GRAY, BLACK }), which Effective Java explicitly recommends over int constants because it gives you type safety, a working switch, and a meaningful toString for free.
- ✓The Java trap: The default JVM thread stack is roughly 512 KB to 1 MB (tunable with -Xss), so a straightforward recursive DFS on a graph with a long chain throws StackOverflowError well before you might expect from a language that otherwise feels unconstrained.
- ✓O(V+E), and the constant-factor lever specific to Java is boxing: a HashMap<Integer, State> autoboxes every node ID into an Integer object on every put/get, while BitSet or a plain int[] state array (when IDs are small dense integers) avoids that allocation entirely, on a graph with millions of nodes that difference alone is often the dominant cost, not the traversal logic itself.
What Cycle Detection actually is
Cycle Detection in Java: what you actually reach for
Java implementation
import java.util.*;
class CycleDetector {
enum State { WHITE, GRAY, BLACK }
static boolean hasCycle(Map<Integer, List<Integer>> graph) {
Map<Integer, State> state = new HashMap<>();
for (int node : graph.keySet()) state.put(node, State.WHITE);
Deque<int[]> stack = new ArrayDeque<>(); // [node, nextChildIndex]: no recursion, no StackOverflowError
for (int start : graph.keySet()) {
if (state.get(start) != State.WHITE) continue;
stack.push(new int[]{start, 0});
state.put(start, State.GRAY);
while (!stack.isEmpty()) {
int[] frame = stack.peek();
List<Integer> children = graph.getOrDefault(frame[0], List.of());
if (frame[1] < children.size()) {
int child = children.get(frame[1]++);
State s = state.get(child);
if (s == State.GRAY) return true; // back edge
if (s == null || s == State.WHITE) {
state.put(child, State.GRAY);
stack.push(new int[]{child, 0});
}
} else {
state.put(frame[0], State.BLACK);
stack.pop();
}
}
}
return false;
}
}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 Java-specific trap
Performance in Java, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Cycle Detection?
java.util.HashMap for adjacency and state, java.util.ArrayDeque as an explicit stack for the iterative version, and java.util.BitSet as a real, allocation-light alternative to two HashSet<Integer> instances (or two boolean[] arrays) when node IDs are dense, BitSet stores one bit per node instead of boxing every ID into an Integer.
What is the most common Java mistake when implementing Cycle Detection?
The default JVM thread stack is roughly 512 KB to 1 MB (tunable with -Xss), so a straightforward recursive DFS on a graph with a long chain throws StackOverflowError well before you might expect from a language that otherwise feels unconstrained. It is technically a catchable Error (unlike C#'s uncatchable equivalent), but by the time it is thrown the stack is exhausted enough that the catch block itself can fail to run cleanly, so treating it as recoverable in production code is not a reliable strategy, write the iterative version instead.
How does Cycle Detection actually perform in Java?
O(V+E), and the constant-factor lever specific to Java is boxing: a HashMap<Integer, State> autoboxes every node ID into an Integer object on every put/get, while BitSet or a plain int[] state array (when IDs are small dense integers) avoids that allocation entirely, on a graph with millions of nodes that difference alone is often the dominant cost, not the traversal logic itself. 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 trialStill choosing? See the top-rated tools by category 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.