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

Happy Number

Core idea: Repeatedly summing the squares of a number's digits is a deterministic step โ€” each number leads to exactly one next number. So the process is a chain that must eventually either land on 1 (happy) or step onto a number it has already produced (a cycle โ†’ not happy). The whole problem is cycle detection on that chain, and you get two tools for it: a seen set (O(k) space) or Floyd's tortoise-and-hare (O(1) space).

Problem, rephrased

You're handed a positive integer and a strange little machine. Press the button and the machine replaces your number with the sum of the squares of its digits. For example, 19 โ†’ 1ยฒ + 9ยฒ = 1 + 81 = 82. Keep pressing.

A number is happy if, by pressing the button over and over, you eventually reach 1 (and once you hit 1, you stay at 1 forever, since 1ยฒ = 1). A number is unhappy if it never reaches 1 โ€” instead it falls into a loop that cycles forever without ever touching 1.

Your job: given n, return True if n is happy, False otherwise.

Input n Process Output Why
19 19 โ†’ 82 โ†’ 68 โ†’ 100 โ†’ 1 True reaches 1
2 2 โ†’ 4 โ†’ 16 โ†’ 37 โ†’ 58 โ†’ 89 โ†’ 145 โ†’ 42 โ†’ 20 โ†’ 4 โ€ฆ False re-enters 4 โ€” a loop, never 1
7 7 โ†’ 49 โ†’ 97 โ†’ 130 โ†’ 10 โ†’ 1 True reaches 1
1 already 1 True the happiest number

The single button-press โ€” "replace n with the sum of the squares of its digits" โ€” is a fixed function. Call it next_number(n). Everything below is about following next_number and noticing when it loops.

Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

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.