Cycle Detection Implementation in JavaScript
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 JavaScript as in every other language.
- ✓Nothing graph-specific ships in the language or in Node's built-in modules, no equivalent of Python's graphlib.
- ✓Use a Map for node state, not a plain object, an object's keys are coerced to strings, so numeric IDs 1 and "1" collide, and any ID that happens to collide with a property already on Object.prototype (like "constructor") corrupts the initial lookup.
- ✓The JavaScript trap: There is no specified limit on call-stack depth, it depends on the engine, available memory, and how much local state each frame holds, but in practice V8 throws "RangeError: Maximum call stack size exceeded" at a stack depth in the low thousands for a typical recursive function, and a graph with a long dependency chain (a common shape for real data like package or import graphs) hits that easily.
- ✓O(V+E) either way, but a Map lookup for state costs a hash of the key on every access, so representing node IDs as small consecutive integers and using a plain array indexed by ID for state (instead of a Map) removes that hashing cost entirely once the graph is dense enough to make it worth it.
What Cycle Detection actually is
Cycle Detection in JavaScript: what you actually reach for
JavaScript implementation
const WHITE = 0, GRAY = 1, BLACK = 2;
function hasCycle(graph) {
const state = new Map();
for (const node of graph.keys()) state.set(node, WHITE);
for (const start of graph.keys()) {
if (state.get(start) !== WHITE) continue;
// explicit stack: recursion blows the call stack on a long chain
const stack = [[start, 0]];
state.set(start, GRAY);
while (stack.length) {
const frame = stack[stack.length - 1];
const [node, i] = frame;
const children = graph.get(node) || [];
if (i < children.length) {
frame[1] += 1;
const child = children[i];
const s = state.get(child);
if (s === GRAY) return true; // back edge => cycle
if (s === WHITE) {
state.set(child, GRAY);
stack.push([child, 0]);
}
} else {
state.set(node, 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 JavaScript-specific trap
Performance in JavaScript, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Cycle Detection?
Nothing graph-specific ships in the language or in Node's built-in modules, no equivalent of Python's graphlib. The tools you actually have are Map (for O(1)-amortized adjacency and state lookups keyed by arbitrary values, not just strings) and Set, plus a plain array used as an explicit call stack when you need to avoid real recursion.
What is the most common JavaScript mistake when implementing Cycle Detection?
There is no specified limit on call-stack depth, it depends on the engine, available memory, and how much local state each frame holds, but in practice V8 throws "RangeError: Maximum call stack size exceeded" at a stack depth in the low thousands for a typical recursive function, and a graph with a long dependency chain (a common shape for real data like package or import graphs) hits that easily. Because the limit is not specified anywhere, code that passes every test fixture can still fail the first time it sees a deeper real graph in production.
How does Cycle Detection actually perform in JavaScript?
O(V+E) either way, but a Map lookup for state costs a hash of the key on every access, so representing node IDs as small consecutive integers and using a plain array indexed by ID for state (instead of a Map) removes that hashing cost entirely once the graph is dense enough to make it worth it. The iterative version's explicit stack array grows the same way any push-heavy array does (V8 grows backing stores geometrically), so pre-sizing it or reusing one across calls avoids repeated reallocation on hot paths. 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 GitHub Copilot 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.