Happy Number
Happy Number is LeetCode 202 (Easy). Start from a positive integer n and keep replacing it with the sum of the squares of its digits. If this ever reaches 1, n is happy and you return true. If it goes round in a loop that never includes 1, return false.
ncan be as large as 2³¹ − 1, so you cannot list every value up front; you only ever know the next one.
- 1 <= n <= 2³¹ - 1
Intuition
Every number has exactly one next number, so the values form a chain like a linked list whose next pointer is computed instead of stored. The chain cannot grow forever: the first replacement takes any allowed n below 1,000, and every value below 1,000 maps to 243 or less. With only that many values to visit, the chain must repeat, and the only question is whether it repeats at 1 or somewhere else.
1 maps to itself, so a chain that reaches 1 stays there. Floyd's slow and fast pointers settle the rest: inside a loop the fast one gains one step per round, so it must land on the slow one.
"Apply the same rule over and over and decide whether it ends or repeats" is cycle detection on an implicit linked list. Each value is a node and the rule is its next pointer, so the tools for a linked-list cycle carry over unchanged.
Approach
Before reading on, follow the chain from n = 2 by hand until a number repeats. Then ask how a program could notice that repeat without storing every number it has seen.
Two ways to notice the loop
Move one pointer one hop and the other two hops; a meeting away from 1 means a loop.
- Two integers: no memory grows with the chain.
- Same trick: as finding a cycle in a linked list.
Store each value you visit and stop when the next one is already stored.
- Direct: the code reads like the problem statement.
- Extra memory: one entry per visited value.
Both follow the same chain and stop at 1 or at the first repeat. The steps, code and live demo use the two pointers; the set version follows the demo.
Write the next-number rule once
Peel off digits with % 10 and // 10, square each one and add them up. Both pointers call this one helper, so they walk exactly the same chain, and arithmetic avoids turning the number into a string on every hop.
Move slow one hop and fast two hops
Start slow and fast at n. Each round, slow takes one hop and fast takes two. Once both are inside a loop, the distance from fast back to slow shrinks by one each round, so fast cannot jump over slow; it lands on it.
Return true when fast reaches 1
Check fast first. Since 1 squared is 1, a chain that reaches 1 never leaves it, so the number is happy. fast is ahead of slow, so it gets to 1 first and the loop ends sooner.
Return false when they meet anywhere else
If slow equals fast and the value is not 1, both are going round a loop. 1 cannot be part of that loop, because 1 only leads back to 1, so the chain will never reach 1.
Code in Python, C++ and Java
true.false.false.Remember every number in a set
Keep a set of every value the chain has produced. Before each hop, stop if the current value is 1 or is already in the set; a value seen twice means the chain has started to repeat. The set holds at most a few dozen numbers here, because the chain is short once it drops below 1,000.
Common pitfalls
Looping until the number becomes 1
while n != 1:
n = next_number(n)
return Trueif fast == 1:
return True
if slow == fast:
return FalseThis never stops on an unhappy number. From n = 2 the values run 4, 16, 37, 58, 89, 145, 42, 20 and back to 4, forever, so the function hangs instead of returning false.
Testing for a meeting before testing for 1
if slow == fast:
return False
if fast == 1:
return Trueif fast == 1:
return True
if slow == fast:
return FalseWhen both pointers reach 1 in the same round they are also equal, and this order calls that a loop. n = 1 and n = 10 both return false, though both are happy.
Starting both pointers at n under a while-not-equal loop
slow = fast = n
while slow != fast:
...
return slow == 1slow = fast = n
while True:
slow = next_number(slow)
fast = next_number(next_number(fast))
...The pointers start equal, so the loop body never runs and the answer is just n == 1. n = 19 is happy, but this returns false. Move the pointers before comparing them, or start fast one hop ahead.
Complexity
n. After that every value is below 1,000, so the number of rounds and the work per hop are both bounded by a constant. Only slow and fast are stored.Happy Number FAQ
Which numbers from 1 to 100 are happy?
There are twenty happy numbers from 1 to 100: 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97 and 100. Reordering the digits or adding zeros does not change the sum of squares, which is why 13 and 31, or 1, 10 and 100, come in groups.
Do all unhappy numbers end up in the same loop?
Yes. Every unhappy number eventually enters 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. Checking all values below 1,000 proves it, since every input lands there after one hop. So while n != 1 and n != 4 also works, but it relies on that fact instead of detecting the loop.
Where else is the slow and fast pointer idea used?
Anywhere a value has exactly one next value. Linked List Cycle uses it on real next pointers, and Linked List Cycle II extends it to find where the loop starts.