← Back to Leo Academy Masterclass

Problem #202: Happy Number

Easy Hashmap

Intuition & Strategy Breakdown

Calculate sum of squared digits repeatedly. Use Floyd's cycle detection or hash set to detect loop; return true if reaching 1.

Python Solution

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n not in seen:
            seen.add(n)
            n = sum(int(char)**2 for char in str(n))
            if n == 1:
                return True
        return False

Java Solution

class Solution {
    public boolean isHappy(int n) {
        Set seen = new HashSet<>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            int sum = 0;
            while (n > 0) {
                int digit = n % 10;
                sum += digit * digit;
                n /= 10;
            }
            n = sum;
        }
        return n == 1;
    }
}
Watch Interactive Video on Leo Academy Main App