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 - Hash Set Approach INPUT n = 19 Digit Breakdown: 1 9 Sum of squares: 1² + 9² = 1 + 81 = 82 Hash Set tracks seen numbers seen = {} ALGORITHM STEPS 1 19: 1²+9²=82 Add 19 to set 2 82: 8²+2²=68 Add 82 to set 3 68: 6²+8²=100 Add 68 to set 4 100: 1²+0²+0²=1 Reached 1! Hash Set Contents: 19 82 68 100 19 --> 82 --> 68 --> 100 --> 1 No cycle detected! Number reached 1 FINAL RESULT Output: true 19 is a HAPPY NUMBER! Reached 1 in 4 steps No infinite loop [OK] Key Insight: Use a Hash Set to detect cycles. If the same number appears twice, we have an infinite loop (not happy). If we reach 1, the number is happy. Hash Set provides O(1) lookup for cycle detection. TutorialsPoint - Happy Number | Hash Set Approach
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