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

Cycle Detection Implementation in JavaScript

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 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 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 JavaScript: what you actually reach for

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.

JavaScript implementation

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. For anything that will run on untrusted or generated input rather than a small fixture in a test file, write the DFS iteratively from the start instead of retrofitting it after a stack overflow shows up in production.
javascript
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 Free

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

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

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. 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 JavaScript, 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 JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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

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 GitHub Copilot 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.