11. Happy Number
easyAsked at N26Determine if a number eventually reaches 1 when repeatedly replaced by the sum of squares of its digits. N26 uses it to gauge cycle-detection instinct before harder ACH retry-loop questions.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
A happy number is defined by replacing the number with the sum of squares of its digits and repeating until it reaches 1 or loops endlessly. Return true if n is happy, otherwise false.
Constraints
1 <= n <= 2^31 - 1
Examples
Example 1
n=19trueExample 2
n=2falseApproaches
1. Hash set cycle detection
Track every seen value; return false when one repeats.
- Time
- O(log n)
- Space
- O(log n)
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = [...String(n)].reduce((s,d)=>s+d*d,0);
}
return n === 1;Tradeoff:
2. Floyd's tortoise and hare
Two pointers running at different speeds detect any cycle in O(1) memory. If they meet at 1 it is happy; otherwise it is a non-1 cycle.
- Time
- O(log n)
- Space
- O(1)
function isHappy(n) {
const next = x => [...String(x)].reduce((s,d)=>s+d*d,0);
let slow = n, fast = next(n);
while (fast !== 1 && slow !== fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast === 1;
}Tradeoff:
N26-specific tips
N26 likes Floyd's answer because it mirrors how their ACH retry workers detect a payment stuck in a bounce-loop without holding state in Redis.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More N26 coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Plus One
- 8. Merge Sorted Array