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