Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

happy-number.py

math-geometry/happy-number.py · Python · 1.3 KiB · 2026-02-17 21:04

Back to folder
# Try with a couple of numbers: realize that either a) you reach 1 (happy) or b) you enter a cycle that doesn't include 1 (not happy). Use a set to track seen numbers. Or use Floyd's Cycle Detection Algorithm with fast and slow pointers.
# math,geometry

# O(log n) time | O(log n) space
# time complexity to get number of digit in a number with base 10 is = ⌊log₁₀(n)⌋ + 1
# “How many times can I divide n by the base before it becomes zero?”
def isHappy(n: int) -> bool:
    seen = set()
    cur = n
    while True:
        square = get_square_of_digits(cur)
        if square == 1:
            return True
        elif square in seen:
            break
        seen.add(square)
        cur = square
    return False

# O(log n) time | O(1) space
def isHappy_cycle_detection(n: int) -> bool:
    slow = n
    fast = get_square_of_digits(n)
    while slow != fast:
        slow = get_square_of_digits(slow)
        fast = get_square_of_digits(fast)
        fast = get_square_of_digits(fast)
    return slow == fast == 1


def get_square_of_digits(n: int) -> int:
    sum_squares = 0
    while n:
        digit = n % 10
        sum_squares = digit ** 2
        n //= 10
    return sum_squares

def get_square_of_digits1(n: int) -> int:
    return sum([pow(int(x),2) for x in str(n)])