Happy Number

Write an algorithm to determine if a number n is happy. A happy number is 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.

Example 1
Input: n = 19
Output: true
Explanation: 1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1
Example 2
Input: n = 2
Output: false
Explanation: The process eventually enters a cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 ...

Solution Approach

Use Floyd's cycle detection (slow and fast pointers) on the sequence of digit-square sums. If the sequence reaches 1, the number is happy. If slow meets fast (cycle detected), it is not happy.

  • Define a helper sumOfSquares(n) that computes sum of squares of digits.
  • Move slow one step and fast two steps at a time.
  • If fast reaches 1, return true.
  • If slow equals fast (cycle), return false.
Java
class Solution {
    private int sumOfSquares(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            sum += d * d;
            n /= 10;
        }
        return sum;
    }

    public 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;
    }
}
Complexity Analysis:

Time complexity: O(log n) per step, O(log n) steps. Effectively O(log² n) overall.
Space complexity: O(1). Floyd's cycle detection uses constant space.