Sum of squared digits, detect a cycle
Replace n with the sum of the squares of its digits. If you hit 1, it is happy. If you see a number twice, you are in a loop — not happy.
The map of n → digit-square-sum is finite, so you either reach 1 or a cycle (the famous 4-loop).
Algorithm
- While
n ≠ 1andnis new, record it and replace it with the digit-square sum. - Return whether you landed on 1.
- Time
- O(log n)
- Space
- O(log n)
class Solution: def isHappy(self, n: int) -> bool: seen: set[int] = set() while n != 1 and n not in seen: seen.add(n) n = sum(int(d) ** 2 for d in str(n)) return n == 1