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 Alex Chen, 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.
Practice these live with InterviewChamp.AI
Drill Happy Number and other N26 interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →