SDE & MLE Prep

202. Happy Number

Problem

Repeatedly replace n by the sum of the squares of its digits. n is happy if this reaches 1; otherwise it loops forever in a cycle without 1. Decide whether n is happy.

Example: 19 → true (1 + 81 = 82 → 68 → 100 → 1); 2 → false

Repeatedly summing squared digits either reaches 1 or loops. Detect the loop with Floyd (or a seen-set).

Complexity: O(log n) per step; the sequence quickly drops below 243.

class Solution:
    def isHappy(self, n: int) -> bool:
        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, fast = nxt(slow), nxt(nxt(fast))
        return fast == 1