Coding Interview PatternsHappy Number
EasyFast and Slow Pointers
Happy Number
Explanation & Solution
Description
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals
1(where it will stay), or it loops endlessly in a cycle which does not include1. - Those numbers for which this process ends in
1are happy.
Return true if n is a happy number, and false if not.
Input: n = 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
Constraints
1 <= n <= 2³¹ - 1
Approach
Fast and Slow Pointers pattern
1. Define the Helper Function
- Create a
getNext(num)function that computes the sum of the squares of the digits ofnum - Extract each digit using
num % 10, square it, and add it to a running sum - Divide
numby 10 (integer division) to move to the next digit
2. Initialize Two Pointers
- Set
slowton(the starting number) - Set
fasttogetNext(n)(one step ahead) - These act like the tortoise and hare on the sequence of digit-square sums
3. Traverse the Sequence
- Loop while
fast !== 1andslow !== fast - Move
slowforward by one step:slow = getNext(slow) - Move
fastforward by two steps:fast = getNext(getNext(fast))
4. Determine the Result
- If the loop exits because
fast === 1, the number is happy — returntrue - If the loop exits because
slow === fast(and it's not 1), a cycle was detected that doesn't include 1 — returnfalse
Key Insight
- The sequence of digit-square sums either reaches 1 or enters a cycle — it cannot grow to infinity (the maximum sum for a number with d digits is 81d, which is always smaller than the original number for large values)
- This is the same Floyd's Cycle Detection technique used for linked lists, applied to an implicit sequence
Time
O(log n)the number of digits determines how quickly the sequence convergesSpace
O(1)only two variables are used, no hash set needed