Skip to content
Bill Liao
Go back

Happy Number

Edit page

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

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:

Approach: Floyd’s Cycle Detection (Two Pointers)

Algorithm

  1. Define a helper that computes the sum of the squares of a number’s digits
  2. Use two pointers: a slow one (moves one step) and a fast one (moves two steps)
  3. If there is a cycle that does not include 1, the two pointers will meet
  4. If the fast pointer reaches 1, the number is happy

Time & Space Complexity

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. 1² + 9² = 82
  2. 8² + 2² = 68
  3. 6² + 8² = 100
  4. 1² + 0² + 0² = 1

Since the sequence reaches 1, 19 is happy.

For n = 2:

  1. 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

  1. Cycle Detection: Either 1 (happy) or a fixed cycle (unhappy) is reached
  2. Two Pointers: Floyd’s algorithm uses O(1) space instead of a set
  3. Digit Square Sum: Each step is at most 81 * (number of digits), which shrinks quickly
  4. O(1) Space Alternative: The hash set version is simpler but uses O(cycle length) space
  5. Guaranteed Termination: The process always ends in 1 or a known cycle

Edit page
Share this post:

Previous Post
Generate Parentheses
Next Post
Integer to English Words