Happy Number

Easyhash-tablemathtwo-pointers
Category: Math & Geometry
Companies that ask this question:
AmazonGoogleFacebookUber

Approach

Happy Number

Problem Statement

A happy number is a number where the process of repeatedly replacing the number by the sum of squares of its digits eventually leads to 1.

Examples

Example 1:

Input: n = 19
Output: true
Explanation: 
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1

Approach

Use Floyd's cycle detection (slow/fast pointers) or hash set to detect cycles.

Complexity

  • Time: O(log n)
  • Space: O(log n) with hash set, O(1) with two pointers

Solution

java
1class Solution {
2    public boolean isHappy(int n) {
3        Set<Integer> seen = new HashSet<>();
4        while (n != 1 && !seen.contains(n)) {
5            seen.add(n);
6            n = sumSquares(n);
7        }
8        return n == 1;
9    }
10    
11    private int sumSquares(int n) {
12        int sum = 0;
13        while (n > 0) {
14            int digit = n % 10;
15            sum += digit * digit;
16            n /= 10;
17        }
18        return sum;
19    }
20}
Loading visualizer...