Easy · Seen-State Set
Understand → Visualise → Practice.
Repeatedly replace n by the sum of the squares of its decimal digits; return whether the process reaches 1.
Repeating the digit-square sum either reaches 1 or falls into a loop. Remember every value seen; seeing one again means it will never reach 1.
Replace n with the sum of the squares of its decimal digits.
Add each value to a set before moving on.
Return true on 1 and false when a value repeats.
O(log n) per step; the sequence quickly drops below a few hundred, so the total is small. O(k) space for k values seen.
Without cycle detection the loop runs forever for unhappy numbers.
Read the full guide first: Hash Maps and Hash Sets.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.