A number is "happy" if repeatedly replacing it with the sum of the squares of its digits eventually reaches 1. Determine whether a given number n is happy.
Example
Input n = 19
Output true
Key Pointers
If a number isn't happy, the sequence of sums-of-squares enters a repeating cycle instead of growing forever — it never just diverges.
Detecting a repeated value is therefore enough to conclude "not happy," no need to bound how many steps to try.
This is the same shape as cycle detection in a linked list — a hash set of visited values is the simplest way to catch the repeat.
Step-by-Step Analysis
Create an empty set seen.
Loop: if n == 1, return True.
If n is already in seen, return False — a cycle was detected.
Otherwise add n to seen, replace n with the sum of the squares of its digits, and repeat.
Complexity
Time: O(log n) per step, bounded number of distinct states — Space: O(log n)
Code
def isHappy(n: int) -> bool:
seen = set()
while n != 1:
if n in seen:
return False
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return True
Code Explanation
How the solution above works, piece by piece.
Repeatedly replace n with the sum of the squares of its digits.
If it reaches 1, the number is happy.
Otherwise the sequence must eventually repeat a value (numbers quickly shrink below a few hundred), and a repeat means an endless loop. seen catches the first repeat → False.
str(n) is a simple way to get the digits.
Runs in effectively O(log n) steps; Floyd's cycle detection could replace the set to use O(1) memory.
Visual Walkthrough
Running it on n = 19:
Each step replaces the number with the sum of the squares of its digits. The seen set detects a loop; here the sequence reaches 1 in four steps.