Happy Number: Hash Set vs Floyd's Cycle Detection

Happy Number (LeetCode 202) asks: start from n, repeatedly replace it with the sum of the squares of its digits, and report whether you eventually reach 1. For example 19 goes 19 → 82 → 68 → 100 → 1, so it is happy. 2 never reaches 1; it falls into the loop 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Why the process always ends in a loop or at 1

The key observation interviewers want you to say out loud: for any number with d digits, the next value is at most 81·d. A 4-digit number maps to at most 324, and anything at or below 999 maps to at most 243. So after a step or two the sequence is trapped below 1000, and a sequence of integers in a finite range must either hit 1 or repeat. That is why "detect a cycle" is a complete answer and not a guess.

Approach 1: remember what you have seen

def next_num(n):
    total = 0
    while n:
        n, d = divmod(n, 10)
        total += d * d
    return total

def is_happy(n):
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        n = next_num(n)
    return n == 1

Time is O(log n) per step and the number of steps is bounded by the small range above; space is the size of the set.

Approach 2: Floyd's tortoise and hare, O(1) space

Treat next_num as a linked list's next pointer. Move slow one step and fast two steps; if there is a cycle they meet, and if fast reaches 1 the number is happy.

def is_happy(n):
    slow, fast = n, next_num(n)
    while fast != 1 and slow != fast:
        slow = next_num(slow)
        fast = next_num(next_num(fast))
    return fast == 1

What to say in the interview

  1. State the 81·d bound so the cycle argument is rigorous.
  2. Give the set version first; it is the clearest.
  3. Offer Floyd as the constant-space follow-up and connect it to Linked List Cycle, which shows you recognize the pattern rather than memorizing a solution.
  4. Mention the trivia answer (every unhappy number reaches the 4 → … → 4 loop) only as a remark, not as the solution.

If you practice these explanations under time pressure, a tool such as AI coding interview assistant can give real-time hints during mock coding rounds.

Disclosure: I work on Linkjob AI.

Disclosure: I work on Linkjob AI.