Happy number

July 28, 2022

math-and-geometry

Problem URL: Happy number

We will calculate the next number, and memoize it. If it's already in the memo, that means we have a cycle, then we return false. Otherwise the number will end up on to be 1. Then we break the loop and return true.

class Solution:
    def isHappy(self, n: int) -> bool:
        memo = set()
        while n != 1:
            n = sum(int(i) ** 2 for i in str(n))
            if n in memo:
                return False
            memo.add(n)
        return True

Time Complexity: O(n)
Space Complexity: O(n)