Happy Number
Difficulty: Easy
Take a positive number and keep replacing it with the sum of the squares of its digits.
If you reach 1, the number is happy. If the numbers loop forever without reaching 1, it's not happy.
Given a number, return whether it's happy.
Examples
Input: n = 19
Output: true
19 -> 1²+9² = 82 -> 8²+2² = 68 -> 6²+8² = 100 -> 1²+0²+0² = 1. It reaches 1, so it's happy.
Input: n = 2
Output: false
2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 - it loops back to a number already seen (4) without ever reaching 1.
Input: n = 1
Output: true
It's already 1.
Constraints
1 <= n <= 2^31 - 1
Approach
The direct way simulates the process, keeping a set of every number produced. Reaching 1 means happy. Producing a number already in the set means it's stuck in a loop, so it's not happy.
You can skip remembering every number. The sequence either reaches 1 or loops, just like a linked list that ends or cycles. So the "fast and slow pointer" trick works: one value takes one step at a time, another takes two. If they land on the same number, the process is looping. The number is happy only if that shared number is 1.
Solutions
Brute Force - Hash Set of Seen Values
Keep replacing the number with the sum of its squared digits, recording each value in a set. Return true if it becomes 1, or false if it repeats a value.
function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = sumOfSquaredDigits(n);
}
return n === 1;
}
function sumOfSquaredDigits(n) {
let sum = 0;
while (n > 0) {
const digit = n % 10;
sum += digit * digit;
n = Math.floor(n / 10);
}
return sum;
}Time: O(log n) per step to compute digit squares, over a bounded number of steps before a repeat occurs · Space: O(k), where k is the number of distinct values produced before the sequence reaches 1 or repeats
Optimal - Fast and Slow Pointers (Cycle Detection)
Move one value ('slow') one step of the process at a time, and another ('fast') two steps. If the sequence loops, fast will land on the same number as slow. The number is happy only if fast reaches 1.
function isHappy(n) {
let slow = n;
let fast = sumOfSquaredDigits(n);
while (fast !== 1 && slow !== fast) {
slow = sumOfSquaredDigits(slow);
fast = sumOfSquaredDigits(sumOfSquaredDigits(fast));
}
return fast === 1;
}
function sumOfSquaredDigits(n) {
let sum = 0;
while (n > 0) {
const digit = n % 10;
sum += digit * digit;
n = Math.floor(n / 10);
}
return sum;
}Time: O(log n) per step, over a bounded number of steps · Space: O(1)