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:
- Start with any positive integer
- Replace the number by the sum of the squares of its digits
- Repeat this process until either:
- β
The number becomes
1(happy!) - β It gets stuck in a cycle that never reaches
1(not happy)
- β
The number becomes
Example: Let's check if 19 is happy:
19β1Β² + 9Β² = 1 + 81 = 8282β8Β² + 2Β² = 64 + 4 = 6868β6Β² + 8Β² = 36 + 64 = 100100β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
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
β‘ Linearithmic
Space Complexity
O(1)
Only uses two pointer variables, no additional data structures
β Linear Space
Constraints
- 1 β€ n β€ 231 - 1
- Follow up: Could you solve this with O(1) extra space?
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code