LeetCode #202 Easy

Happy Number

Happy Number is LeetCode 202 (Easy). Start from a positive integer n and keep replacing it with the sum of the squares of its digits. If this ever reaches 1, n is happy and you return true. If it goes round in a loop that never includes 1, return false.

  • n can be as large as 2³¹ − 1, so you cannot list every value up front; you only ever know the next one.
Constraints
  • 1 <= n <= 2³¹ - 1
mathtwo-pointerscycle-detection
Open on LeetCode ↗
02

Intuition

Every number has exactly one next number, so the values form a chain like a linked list whose next pointer is computed instead of stored. The chain cannot grow forever: the first replacement takes any allowed n below 1,000, and every value below 1,000 maps to 243 or less. With only that many values to visit, the chain must repeat, and the only question is whether it repeats at 1 or somewhere else.

1 maps to itself, so a chain that reaches 1 stays there. Floyd's slow and fast pointers settle the rest: inside a loop the fast one gains one step per round, so it must land on the slow one.

How to spot this pattern

"Apply the same rule over and over and decide whether it ends or repeats" is cycle detection on an implicit linked list. Each value is a node and the rule is its next pointer, so the tools for a linked-list cycle carry over unchanged.

03

Approach

Try it first

Before reading on, follow the chain from n = 2 by hand until a number repeats. Then ask how a program could notice that repeat without storing every number it has seen.

1

Write the next-number rule once

Peel off digits with % 10 and // 10, square each one and add them up. Both pointers call this one helper, so they walk exactly the same chain, and arithmetic avoids turning the number into a string on every hop.

2

Move slow one hop and fast two hops

Start slow and fast at n. Each round, slow takes one hop and fast takes two. Once both are inside a loop, the distance from fast back to slow shrinks by one each round, so fast cannot jump over slow; it lands on it.

3

Return true when fast reaches 1

Check fast first. Since 1 squared is 1, a chain that reaches 1 never leaves it, so the number is happy. fast is ahead of slow, so it gets to 1 first and the loop ends sooner.

4

Return false when they meet anywhere else

If slow equals fast and the value is not 1, both are going round a loop. 1 cannot be part of that loop, because 1 only leads back to 1, so the chain will never reach 1.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isHappy(self, n: int) -> bool:
▶3 def next_number(x: int) -> int:
▶4 total = 0
▶5 while x > 0:
▶6 x, digit = divmod(x, 10)
▶7 total += digit * digit
▶8 return total
▶9 
▶10 slow = fast = n
▶11 while True:
▶12 slow = next_number(slow)
▶13 fast = next_number(next_number(fast))
▶14 if fast == 1:
▶15 return True
▶16 if slow == fast:
▶17 return False
slow's hop1982681001slow, fastboth pointers start at 19
slow19
fast19
Both pointers start on 19. The grey numbers ahead are the rest of the chain; the code never stores them, it only works out the next one when a pointer hops.
slow's hop19→1²+9²=821982681001slowfastslow to 82, fast to 68: not 1, not equal
round1
slow82
fast68
Slow hops once: 19 becomes 82. Fast hops twice and is on 68. Fast is not on 1 and the two are on different numbers, so neither stop rule applies and the race goes on.
slow's hop82→8²+2²=681982681001slowfastslow to 68, fast to 1 → 19 is happy
round2
slow68
fast1
Fast took two hops and landed on 1. 1 squared is 1, so the chain stays at 1 from here on: 19 is happy and the code returns true.
slow's hop1982681001answer: true, the chain ends at 1
rounds2
answertrue
The whole chain: 19 → 82 → 68 → 100 → 1. It ends at 1, which points to itself.
05

Remember every number in a set

Keep a set of every value the chain has produced. Before each hop, stop if the current value is 1 or is already in the set; a value seen twice means the chain has started to repeat. The set holds at most a few dozen numbers here, because the chain is short once it drops below 1,000.

▶1class Solution:
▶2 def isHappy(self, n: int) -> bool:
▶3 seen = set()
▶4 while n != 1 and n not in seen:
▶5 seen.add(n)
▶6 total = 0
▶7 while n > 0:
▶8 n, digit = divmod(n, 10)
▶9 total += digit * digit
▶10 n = total
▶11 return n == 1
06

Common pitfalls

Looping until the number becomes 1

✗ Wrong
while n != 1:
    n = next_number(n)
return True
✓ Right
if fast == 1:
    return True
if slow == fast:
    return False

This never stops on an unhappy number. From n = 2 the values run 4, 16, 37, 58, 89, 145, 42, 20 and back to 4, forever, so the function hangs instead of returning false.

Testing for a meeting before testing for 1

✗ Wrong
if slow == fast:
    return False
if fast == 1:
    return True
✓ Right
if fast == 1:
    return True
if slow == fast:
    return False

When both pointers reach 1 in the same round they are also equal, and this order calls that a loop. n = 1 and n = 10 both return false, though both are happy.

Starting both pointers at n under a while-not-equal loop

✗ Wrong
slow = fast = n
while slow != fast:
    ...
return slow == 1
✓ Right
slow = fast = n
while True:
    slow = next_number(slow)
    fast = next_number(next_number(fast))
    ...

The pointers start equal, so the loop body never runs and the answer is just n == 1. n = 19 is happy, but this returns false. Move the pointers before comparing them, or start fast one hop ahead.

07

Complexity

Time
O(log n)
Space
O(1)
The first hop reads about log₁₀ n digits of n. After that every value is below 1,000, so the number of rounds and the work per hop are both bounded by a constant. Only slow and fast are stored.
08

Happy Number FAQ

Which numbers from 1 to 100 are happy?

There are twenty happy numbers from 1 to 100: 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97 and 100. Reordering the digits or adding zeros does not change the sum of squares, which is why 13 and 31, or 1, 10 and 100, come in groups.

Do all unhappy numbers end up in the same loop?

Yes. Every unhappy number eventually enters 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. Checking all values below 1,000 proves it, since every input lands there after one hop. So while n != 1 and n != 4 also works, but it relies on that fact instead of detecting the loop.

Where else is the slow and fast pointer idea used?

Anywhere a value has exactly one next value. Linked List Cycle uses it on real next pointers, and Linked List Cycle II extends it to find where the loop starts.