</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Cycle Detection

What is this?

Some processes step from one state to the next in a fixed, repeatable way. If such a process ever lands on a state it has visited before, it is stuck in a loop and will repeat forever. The trick here is to remember every state you have seen in a hash set, so the moment one shows up twice you have caught the loop โ€” just like noticing you have walked past the same shop twice and realizing you are going in circles.

flowchart TD A["Start at a state"] --> B["Compute the next state"] B --> C["Have I seen this state before"] C --> D["Yes so it is a cycle"] C --> E["No so record it and continue"] E --> B

๐Ÿ’ก Fun fact: There is a clever alternative that needs almost no memory โ€” Floyd's "tortoise and hare", where one pointer moves twice as fast as the other and they are guaranteed to collide inside any loop. Robert Floyd, who won the Turing Award, is credited with it, though he never published the algorithm himself.

๐Ÿ”“ The 1 problem in this chapter is free. Sign in with Google or Microsoft to start solving.


Core idea: When a process moves deterministically from one state to the next, it either reaches a goal or revisits a state it's already been in โ€” and a revisit means it will loop forever. A set of seen states detects that loop; fast/slow pointers detect it in O(1) space.


The shape

The rho shape: a tail (start, a, b) leading into a cycle (c, d, e) where revisiting c means an endless loop

If you ever see the same state twice, the future repeats โ€” so:

  • Seen-set: record each state; stop on the goal (success) or on a repeat (cycle). O(states) time and space.
  • Floyd's tortoise & hare: a slow pointer (1 step) and fast pointer (2 steps) over next(); if they meet, there's a cycle โ€” O(1) space.

The problem

Cycle detection flowchart: Happy Number solved by a seen-set (stop on 1 or a repeat) or Floyd's fast/slow pointers in O(1) space

  • Happy Number โ€” repeatedly replace n with the sum of squares of its digits; it reaches 1 (happy) or falls into a fixed cycle. A seen-set spots the repeat; fast/slow does it without storing states.

Key takeaways

  • Deterministic next-state โ‡’ either a goal or a cycle โ€” and a repeated state proves the cycle.
  • Seen-set is the simplest detector (O(n) space); fast/slow trades it down to O(1).
  • The same pattern appears on linked lists (Linked List Cycle) and any functional graph.
  • Why interviewers like it: it tests whether you recognize "this will loop" and know two ways to catch it.

Problem: Happy Number.

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.