LeetEye LeetEye
Easy Math & Geometry ~5 min

Happy Number

math-and-geometry happy-number

Problem

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

Examples

Example 1
Input: n = 19
Output: true
1² + 9² = 82 -> 8² + 2² = 68 -> 6² + 8² = 100 -> 1² + 0² + 0² = 1
Example 2
Input: n = 2
Output: false
Key Insight

This is cycle detection. Use Floyd's algorithm (slow/fast pointers) or a hash set.

Cycle detection: sequence either reaches 1 or cycles. Use hash set to detect repeats, or Floyd's fast/slow pointers.

How to Approach This Problem

Pattern Recognition: When you see keywords like happy number math-and-geometry, think Math & Geometry.

Step-by-Step Reasoning

1 The sequence must cycle or reach 1 because:
Answer: Sum of digit squares has bounded values
For any number, digit-square-sum is bounded. Eventually repeats or hits 1.
2 To detect cycle, we can use:
Answer: Either
Hash set: check if seen. Floyd's: if slow meets fast, cycle exists.
3 In Floyd's algorithm:
Answer: Slow advances 1 step, fast advances 2
If there's a cycle, fast will "lap" slow and meet.
4 Number is happy if:
Answer: Sequence reaches 1
Happy numbers eventually reach 1 and stay there (1->1).
5 Number is NOT happy if:
Answer: B and C
Cycle detected that doesn't include 1 means it will loop forever.

Solution

def isHappy(n: int) -> bool:
    def get_next(num):
        total = 0
        while num > 0:
            digit = num % 10
            total += digit * digit
            num //= 10
        return total
    
    # Floyd's cycle detection
    slow = n
    fast = get_next(n)
    
    while fast != 1 and slow != fast:
        slow = get_next(slow)
        fast = get_next(get_next(fast))
    
    return fast == 1

Complexity Analysis

Time O(log n)
Space O(1)

Master This Pattern

Build intuition with interactive MCQs. Practice Math & Geometry problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye