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 if not.

Input & Output

Example 1 — 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 — Unhappy Number
$ Input: n = 2
Output: false
💡 Note: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. We detect a cycle that doesn't include 1, so 2 is not happy.
Example 3 — Single Digit Happy
$ Input: n = 1
Output: true
💡 Note: 1 → 1² = 1. Already at 1, so it's happy by definition.

Constraints

  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Happy Number: Transform Until 1 or CycleHappy Path: 19 → 82 → 68 → 100 → 1 ✓19826810011² + 9² → 8² + 2² → 6² + 8² → 1² + 0² + 0² → Happy!Unhappy Path: 2 → 4 → 16 → 37 → ... → Cycle ✗Enters infinite cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4🎯 Key Insight: Either reach 1 or detect cycle
Understanding the Visualization
1
Input
Start with positive integer n
2
Transform
Replace with sum of squares of digits
3
Check
Reaches 1 (happy) or cycles (unhappy)
Key Takeaway
🎯 Key Insight: Every number either reaches 1 (happy) or enters an infinite cycle (unhappy)
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
125.0K Views
Medium Frequency
~15 min Avg. Time
2.9K 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