Happy Number - Problem

Imagine a magical transformation that turns numbers into either happy numbers or traps them in an endless cycle! 🎯

A happy number is defined by a fascinating process:

  1. Start with any positive integer
  2. Replace the number by the sum of the squares of its digits
  3. Repeat this process until either:
    • βœ… The number becomes 1 (happy!)
    • ❌ It gets stuck in a cycle that never reaches 1 (not happy)

Example: Let's check if 19 is happy:

  • 19 β†’ 1Β² + 9Β² = 1 + 81 = 82
  • 82 β†’ 8Β² + 2Β² = 64 + 4 = 68
  • 68 β†’ 6Β² + 8Β² = 36 + 64 = 100
  • 100 β†’ 1Β² + 0Β² + 0Β² = 1 βœ…

Since we reached 1, the number 19 is happy!

Your task: Write an algorithm that returns true if the given number n is happy, and false otherwise.

Input & Output

example_1.py β€” Happy Number
$ Input: n = 19
β€Ί Output: true
πŸ’‘ Note: 19 β†’ 1Β² + 9Β² = 82 β†’ 8Β² + 2Β² = 68 β†’ 6Β² + 8Β² = 100 β†’ 1Β² + 0Β² + 0Β² = 1. Since we reached 1, 19 is a happy number.
example_2.py β€” Not Happy Number
$ Input: n = 2
β€Ί Output: false
πŸ’‘ Note: 2 β†’ 4 β†’ 16 β†’ 37 β†’ 58 β†’ 89 β†’ 145 β†’ 42 β†’ 20 β†’ 4. We see that 4 appears again, creating a cycle. Since we never reach 1, 2 is not a happy number.
example_3.py β€” Single Digit Happy
$ Input: n = 7
β€Ί Output: true
πŸ’‘ Note: 7 β†’ 49 β†’ 97 β†’ 130 β†’ 10 β†’ 1. The transformation eventually leads to 1, so 7 is a happy number.

Visualization

Tap to expand
Happy Number Journey19Start821Β²+9Β²=82688Β²+2Β²=681006Β²+8Β²=1001HAPPY!241637Cycle detected!Two Solution Approaches:πŸ”Ή Hash Set: Track all visited numbers O(k) spaceπŸ”Ή Two Pointers: Floyd's algorithm O(1) spaceBoth detect cycles efficiently with O(log n) time complexity
Understanding the Visualization
1
Start the Journey
Begin with your number and prepare to transform it
2
Transform Each Step
Calculate sum of squares of digits at each step
3
Check Destination
Did we reach 1? Or are we in a loop?
4
Detect Cycles
Use either hash set or two pointers to detect infinite loops
Key Takeaway
🎯 Key Insight: Happy numbers either reach 1 or cycle forever. We can detect cycles using either a hash set (intuitive) or Floyd's two-pointer technique (space-optimal).

Time & Space Complexity

Time Complexity
⏱️
O(log n)

Same as hash set approach, but fast pointer does double work

n
2n
⚑ Linearithmic
Space Complexity
O(1)

Only uses two pointer variables, no additional data structures

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ n ≀ 231 - 1
  • Follow up: Could you solve this with O(1) extra space?
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
42.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen