#202

Happy Number

Easy HashSet cycle detection

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Replace a number by the sum of the squares of its digits, again and again. It's "happy" if this reaches 1; otherwise it loops forever. Decide which.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: does "sum of squared digits" reach 1, or loop forever?

Why this works: a repeated number means a loop; a set detects it.

Example: 19

1+81 = 82 → 64+4 = 68 → 36+64 = 100 → 1 ✓ happy

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Looping without detecting repeats — the program never ends for unhappy numbers.

Solve on LeetCode ↗
Complexity
  • Time: O(log n) per step; the sequence quickly drops below a few hundred.
  • Space: O(log n).
Topic: Hashing
🎬 Episodes 37–39: video coming soon