Happy Number
EasyNeetCode 150Top Interview 150 Math & GeometryBlackRockJump TradingNikeSnowflakeXSwiggyProblem
Take a positive integer and replace it by the sum of the squares of its digits. Repeat the process.
Either the value eventually becomes 1 (and stays there), or it enters a loop that never includes 1.
Return true if starting from n the process reaches 1, otherwise false.
Constraints
- 1 ≤ n ≤ 2³¹ − 1
Examples: pick one to animate
Solutions
TimeO(log n)
SpaceO(log n)
Time: The values quickly shrink to at most a few hundred, so the chain is short; each step costs one pass over the digits.
Space: The set holds each distinct value on the chain, a small number of entries.
Keep applying the digit-square step and record every number in a set. If we reach 1 the number is happy. If a number shows up a second time, the chain is stuck in a cycle that does not contain 1.