Happy Number
Decide whether repeatedly summing the squares of a number's digits reaches 1, using cycle detection.
The problem
Start with a positive integer n and keep replacing it with the sum of the squares of its digits. If this process reaches 1, the number is happy; otherwise it loops forever through a cycle of numbers that never contains 1. Return true if n is happy and false if it is not.
Input n = 7
Output true
7 becomes 49, then 97, 130, 10 and finally 1.
Input n = 11
Output false
11 becomes 2, then 4, 16, 37, 58, 89, 145, 42, 20 and 4 again, and the same eight numbers repeat forever.
Key constraint: The sequence either reaches 1 or falls into a loop, and you have to detect the loop instead of running forever.
How to spot the pattern
- A process applies the same function to a value again and again, and the values might repeat.
- You have to tell "ends at 1" apart from "cycles forever", which is cycle detection.
The idea
Think of each number as a node whose next is the sum of the squares of its digits. The sequence is then a linked list that either reaches 1, which points back to itself, or runs into a loop. Floyd's slow and fast pointers find out which: slow applies the step once per round and fast twice, so they must meet, and the number is happy exactly when they meet at 1.
Brute force: Store every number you have seen in a hash set and stop when one repeats, which works but needs extra memory for the set.
Step by step
- 1Write a helper that returns the sum of the squares of a number's digits.
- 2Start
slowatnandfastone step ahead, at the number that followsn. - 3While
fastis not 1 andslowdiffers fromfast, moveslowone step andfasttwo steps. - 4Return
trueiffastreached 1, andfalseif the pointers met somewhere else.
See the pattern move
The fast and slow pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def isHappy(self, n: int) -> bool:
def next_number(x: int) -> int:
total = 0
while x > 0:
x, digit = divmod(x, 10)
total += digit * digit
return total
slow = n
fast = next_number(n)
while fast != 1 and slow != fast:
slow = next_number(slow) # one step
fast = next_number(next_number(fast)) # two steps
return fast == 1Complexity
Time
O(log n)
Space
O(1)
One step costs a pass over the digits; after the first step every value is below 1,000, so only a small, fixed number of rounds follows.
Watch out for
- Starting
slowandfastat the same value and looping while they differ, so the loop never runs at all. - Checking only for 1 without any cycle detection, which runs forever on numbers like 11.
- Returning
slow == 1after the loop: the loop stops as soon asfastreaches 1, whileslowmay still be behind.
Follow-up questions
Why can't the numbers keep growing forever?
A number with d digits maps to at most 81 * d. From 4 digits up that is smaller than the number itself, and a 3-digit number maps to at most 243, so the values drop below 1,000 and stay there. With only finitely many possible values, the sequence has to repeat or reach 1.
Is there a shortcut that avoids cycle detection?
Every unhappy number ends up in the same loop, which passes through 4, so you could stop as soon as you see 4. It is a nice fact to mention, but Floyd's method is the answer that shows the pattern and works for any sequence like this.
In Hinglish
Har number ka next uske digits ke squares ka sum hai, toh yeh ek linked list jaisa hai. Slow aur fast chalao: 1 par mile toh happy, kahin aur mile toh loop hai.