Problem Statement

Happy Number

Here is the game. Take a positive whole number. Square each of its digits (a digit squared just means the digit times itself, like 9 times 9 = 81), then add those squares up. That gives you a new number. Do the same thing again with the new number, over and over. If you eventually land on 1, the original number is "happy." If you never reach 1, you will get stuck going in a circle forever (called a cycle), and the number is "not happy." For example, 19 is happy: 1^2 + 9^2 = 82, 8^2 + 2^2 = 68, 6^2 + 8^2 = 100, 1^2 + 0^2 + 0^2 = 1. The tricky part is spotting when you are stuck in a loop. One neat trick is Floyd's slow/fast pointer technique, which finds a loop without needing extra memory to remember every number you have seen.

easyMathHash TableMath & Number TheoryTime: O(log n) · Space: O(1)

Signals to notice

repeatedly sum squares of digits until 1 or cycledetect cyclehappy = reaches 1

Brute force first

Iterate with a hash set to detect cycles — O(log n) per step, O(log n) space.

The key insight

Floyd's cycle detection: slow does one step, fast does two. If they meet at 1, happy. Otherwise, cycle detected. O(1) space.

Trace it on n = 19

init: slow=19, fast=next(19)=1+81=82
check: fast(82)!=1 and slow(19)!=fast(82) -> enter loop
step1: slow=next(19)=82; fast=next(next(82))=next(68)=100
check: fast(100)!=1 and slow(82)!=fast(100) -> continue
step2: slow=next(82)=68; fast=next(next(100))=next(1)=1
check: fast==1 -> exit loop
return fast==1 -> true (19 is happy)

What must stay true

The digit-square-sum sequence either reaches 1 or enters a cycle. Floyd's detects both without storing history.

Shape of the loop

slow = n; fast = next(n)            # next = sum of squared digits
while fast != 1 and slow != fast:
    slow = next(slow)              # one step
    fast = next(next(fast))        # two steps
return fast == 1                    # met at 1 -> happy

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Using a hash set works but uses space. Floyd's is O(1) space.

Math & Number Theory Pattern