0:00 / 0:00

Keep replacing a number with the sum of its digits squared. Either it reaches one or loops, and slow and fast pointers spot the loop.

▼

The problem

LeetCode 202 (Easy). Repeatedly replace a positive integer n by the sum of the squares of its digits. n is happy if this reaches 1, and not happy if it loops forever without reaching 1.

Examples (LeetCode's): 19 → true (19 → 82 → 68 → 100 → 1) and 2 → false (2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, a loop).

TRY IT ON LEETCODE ▶

The solution

def isHappy(n):
    def nxt(x):
        return sum(int(d) ** 2 for d in str(x))
    slow, fast = n, nxt(n)
    while fast != 1 and slow != fast:
        slow = nxt(slow)
        fast = nxt(nxt(fast))
    return fast == 1

Transcript

Happy Number. Replace a number with the sum of the squares of its digits, and keep going. If you reach one, the number is happy. If you never do, it circles forever, and it isn't.

Take nineteen. One plus eighty-one is eighty-two. Sixty-four plus four, sixty-eight. Thirty-six plus sixty-four, one hundred. Then one. Nineteen is happy!

Now take two. Four, sixteen, thirty-seven, fifty-eight, eighty-nine, one forty-five, forty-two, twenty, and four again. It's been here before, so it goes round forever. Two is not happy.

The easy way: drop every number into a hash set. Stop on one, or on a repeat. It works, but the set keeps a slot for every number it sees.

Here's the trick. Each number has exactly one next number, like a linked list. And it can't grow forever: even nine hundred ninety-nine leads to only two hundred forty-three. So the chain reaches one, or rides a loop, like a carousel.

To catch the loop without a set, send two riders. Slow moves one horse, fast moves two. On the loop, fast gains one horse each turn, so it catches slow within a lap.

In code, next sums the squared digits. Slow starts at n, fast one step ahead. While fast isn't one and the two differ, slow steps once, fast steps twice. Then return whether fast is one.

Try two. Slow on two, fast on four. Then four and thirty-seven. Sixteen and eighty-nine. Thirty-seven and forty-two. Fifty-eight and four, as fast wraps around. Eighty-nine and thirty-seven. One forty-five and eighty-nine. Both land on forty-two. They met, not on one: two is not happy.

Each step squares just a few digits, and the riders meet within a lap, so the time is about order log n. Only two numbers are kept, so the space is order one.

One horse, two horses, catch the loop. That's Happy Number.