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

Cycle Detection Implementation in TypeScript

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 TypeScript as in every other language.
  • ✓Same runtime primitives as JavaScript, Map, Set, arrays, plus a type layer to model the three states as a real enum (enum State { White, Gray, Black }) instead of magic numbers, and generic signatures like ReadonlyMap<T, readonly T[]> to express that the algorithm must not mutate the graph it is given.
  • ✓Model state with an actual enum, not string literals compared with ===, so a typo in a state name is a compile error rather than a silently-false comparison, and use a switch over the enum with an exhaustiveness check (a default branch assigning to a variable typed never) so adding a fourth state later is a compile error everywhere it is unhandled, not a runtime bug discovered in production.
  • ✓The TypeScript trap: If node state is stored as Record<T, State> instead of Map<T, State>, reading a key that was never set gives you State | undefined at the value level but plain State at the type level unless the compiler flag noUncheckedIndexedAccess is enabled, without that flag, an uninitialized node's state compares as not-equal to every real enum member (because it is actually undefined), the traversal silently treats it as unvisited, and a real cycle through that node can go undetected instead of surfacing as a type error you would have caught at compile time.
  • ✓Identical to JavaScript at runtime, the type annotations are erased entirely by the compiler, so a tsc-compiled DFS runs exactly the same bytecode as the equivalent hand-written JavaScript.

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

Same runtime primitives as JavaScript, Map, Set, arrays, plus a type layer to model the three states as a real enum (enum State { White, Gray, Black }) instead of magic numbers, and generic signatures like ReadonlyMap<T, readonly T[]> to express that the algorithm must not mutate the graph it is given.

TypeScript implementation

Model state with an actual enum, not string literals compared with ===, so a typo in a state name is a compile error rather than a silently-false comparison, and use a switch over the enum with an exhaustiveness check (a default branch assigning to a variable typed never) so adding a fourth state later is a compile error everywhere it is unhandled, not a runtime bug discovered in production.
typescript
enum State { White, Gray, Black }

type Graph<T> = ReadonlyMap<T, readonly T[]>;

function hasCycle<T>(graph: Graph<T>): boolean {
  const state = new Map<T, State>();
  for (const node of graph.keys()) state.set(node, State.White);

  for (const start of graph.keys()) {
    if (state.get(start) !== State.White) continue;
    const stack: Array<[T, number]> = [[start, 0]];
    state.set(start, State.Gray);
    while (stack.length > 0) {
      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);        // Map read: `undefined` is a real possibility
        if (s === State.Gray) return true;
        if (s === undefined || s === State.White) {
          state.set(child, State.Gray);
          stack.push([child, 0]);
        }
      } else {
        state.set(node, 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 Free

The TypeScript-specific trap

If node state is stored as Record<T, State> instead of Map<T, State>, reading a key that was never set gives you State | undefined at the value level but plain State at the type level unless the compiler flag noUncheckedIndexedAccess is enabled, without that flag, an uninitialized node's state compares as not-equal to every real enum member (because it is actually undefined), the traversal silently treats it as unvisited, and a real cycle through that node can go undetected instead of surfacing as a type error you would have caught at compile time.

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

Identical to JavaScript at runtime, the type annotations are erased entirely by the compiler, so a tsc-compiled DFS runs exactly the same bytecode as the equivalent hand-written JavaScript. The cost TypeScript adds is at compile time: a deeply generic Graph<T> signature combined with conditional types over the node type can noticeably slow tsc on a large codebase, invisible to the running program but very visible in CI build times. 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 TypeScript, 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 TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Cycle Detection?

Same runtime primitives as JavaScript, Map, Set, arrays, plus a type layer to model the three states as a real enum (enum State { White, Gray, Black }) instead of magic numbers, and generic signatures like ReadonlyMap<T, readonly T[]> to express that the algorithm must not mutate the graph it is given.

What is the most common TypeScript mistake when implementing Cycle Detection?

If node state is stored as Record<T, State> instead of Map<T, State>, reading a key that was never set gives you State | undefined at the value level but plain State at the type level unless the compiler flag noUncheckedIndexedAccess is enabled, without that flag, an uninitialized node's state compares as not-equal to every real enum member (because it is actually undefined), the traversal silently treats it as unvisited, and a real cycle through that node can go undetected instead of surfacing as a type error you would have caught at compile time.

How does Cycle Detection actually perform in TypeScript?

Identical to JavaScript at runtime, the type annotations are erased entirely by the compiler, so a tsc-compiled DFS runs exactly the same bytecode as the equivalent hand-written JavaScript. The cost TypeScript adds is at compile time: a deeply generic Graph<T> signature combined with conditional types over the node type can noticeably slow tsc on a large codebase, invisible to the running program but very visible in CI build times. 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

Studying for this? GitHub Copilot free tiers and academic plans are laid out 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.