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 include 1.
- Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Example 2:
Input: n = 2 Output: false
Constraints:
1 <= n <= 231 - 1
Approach: Floyd’s Cycle Detection (Two Pointers)
Algorithm
- Define a helper that computes the sum of the squares of a number’s digits
- Use two pointers: a slow one (moves one step) and a fast one (moves two steps)
- If there is a cycle that does not include 1, the two pointers will meet
- If the fast pointer reaches 1, the number is happy
Time & Space Complexity
- Time Complexity: O(log n) - the number of steps is small (bounded by the cycle length)
- Space Complexity: O(1) - no set needed for visited numbers
Java Implementation
public class HappyNumber {
/**
* Determine whether n is a happy number.
* @param n Positive integer
* @return true if n is happy
*/
public static boolean isHappy(int n) {
int slow = n;
int fast = sumOfSquares(n);
while (fast != 1 && slow != fast) {
slow = sumOfSquares(slow);
fast = sumOfSquares(sumOfSquares(fast));
}
return fast == 1;
}
private static int sumOfSquares(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
// Test method
public static void main(String[] args) {
System.out.println("Input: n = 19");
System.out.println("Output: " + isHappy(19)); // Expected: true
System.out.println("Input: n = 2");
System.out.println("Output: " + isHappy(2)); // Expected: false
}
}
Alternative Approach: HashSet of Seen Numbers
import java.util.HashSet;
import java.util.Set;
public class HappyNumberSet {
public static boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfSquares(n);
}
return n == 1;
}
private static int sumOfSquares(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
}
Example Walkthrough
For n = 19:
- 1² + 9² = 82
- 8² + 2² = 68
- 6² + 8² = 100
- 1² + 0² + 0² = 1
Since the sequence reaches 1, 19 is happy.
For n = 2:
- 2² = 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> …
The sequence cycles at 4 without ever reaching 1, so 2 is not happy.
Key Points
- Cycle Detection: Either 1 (happy) or a fixed cycle (unhappy) is reached
- Two Pointers: Floyd’s algorithm uses O(1) space instead of a set
- Digit Square Sum: Each step is at most 81 * (number of digits), which shrinks quickly
- O(1) Space Alternative: The hash set version is simpler but uses O(cycle length) space
- Guaranteed Termination: The process always ends in 1 or a known cycle