Notes

Personal notes on various topics

View on GitHub

Intuition

A happy number eventually reaches 1 when repeatedly replaced by the sum of the squares of its digits. If it falls into a cycle (other than 1), it will never reach 1. We can use a set to detect cycles.

Approach

Complexity

Code

class Solution:
    def isHappy(self, n: int) -> bool:
        def get_next(x):
            s = 0
            while x > 0:
                d = x % 10
                s += d**2
                x = x // 10
            return s

        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = get_next(n)

        return n == 1

Back to Problem Statement