Happy Number – Solution & Complexity
1. Understand the Pattern
- Each step replaces
nwith the sum of the squares of its digits. - Because the values stay bounded, the sequence must eventually repeat.
- The number is happy only if that sequence reaches
1.
2. Compute the Digit-Square Sum
- Peel digits off with
% 10and// 10. - Square each digit and accumulate the total.
- This helper drives every step of the process.
3. Detect the Cycle with a Set
- Keep a
seenset of numbers already visited. - Stop with
Falseif a value repeats, orTrueif it reaches1. - This is
O(1)-ish space because the reachable values are bounded.
4. Final Solution and Complexity
- Floyd's slow/fast pointers detect the cycle without a set.
- Time is
O(log n)per step across a bounded number of steps. - Space is
O(1).