sagelearnai

Happy Number

Difficulty: Easy · Pattern: Fast & Slow Pointers · LeetCode #202

Repeatedly replace n with the sum of the squares of its digits. n is happy if this process reaches 1. Otherwise it loops forever in a cycle that doesn't include 1. Return true if n is happy.

Examples

text
19 → 1² + 9² = 82 → 68 → 100 → 1    →  true
2  → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → …   →  false

Hints

  1. The sequence either reaches 1 or enters a cycle. It can't grow forever: for numbers with 4 or more digits, the next value is smaller.
  2. Detecting a cycle in a sequence defined by next(x) is exactly Floyd's tortoise and hare, with no hash set needed.

Approach

Treat x → next(x) as a linked list implicitly defined by a function. Move slow one step and fast two steps until they meet or fast hits 1. Return fast == 1.

A hash set of seen values works too, with O(cycle length) memory. Floyd uses O(1). (Fun fact: every unhappy number eventually enters the single cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.)

Complexity

Time: O(log n) per step and a bounded number of steps. Space: O(1).

Python solution
def isHappy(n):
    def nxt(x):
        s = 0
        while x:
            x, d = divmod(x, 10)
            s += d * d
        return s
    slow, fast = n, nxt(n)
    while fast != 1 and slow != fast:
        slow = nxt(slow)
        fast = nxt(nxt(fast))
    return fast == 1
JavaScript solution
function isHappy(n) {
  const nxt = (x) => { let s = 0; while (x) { const d = x % 10; s += d * d; x = Math.floor(x / 10); } return s; };
  let slow = n, fast = nxt(n);
  while (fast !== 1 && slow !== fast) { slow = nxt(slow); fast = nxt(nxt(fast)); }
  return fast === 1;
}