Taro Logo

Happy Number

Easy
1 views
2 months ago

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

For example:

Example 1:

Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

Example 2:

Input: n = 2 Output: false

Constraints:

1 <= n <= 231 - 1

Sample Answer
# Happy Number

## Problem Description

We are tasked with determining whether a given number `n` is a happy number. A happy number is defined by repeatedly replacing the number by the sum of the squares of its digits. This process continues until either the number becomes 1 (and stays there), or it enters a cycle that doesn't include 1. If the process ends in 1, the number is considered happy. We need to return `true` if `n` is a happy number and `false` otherwise.

For example:

*   If `n = 19`, the sequence is:
    *   1^2 + 9^2 = 82
    *   8^2 + 2^2 = 68
    *   6^2 + 8^2 = 100
    *   1^2 + 0^2 + 0^2 = 1
    Since it ends in 1, 19 is a happy number.
*   If `n = 2`, the process would loop endlessly without reaching 1, so 2 is not a happy number.

## Naive Solution

A naive approach involves simulating the process as described and checking if the number becomes 1. If the process continues for too long without reaching 1, we can assume that it's stuck in a cycle and return `false`.

```python
def is_happy_naive(n):
    seen = set()
    while n != 1:
        if n in seen:
            return False
        seen.add(n)
        n = sum(int(digit)**2 for digit in str(n))
    return True

Optimal Solution

The optimal solution is essentially the same as the naive one because there is no better mathematical trick to find the happy number. However, the code can be cleaned up to be more readable.

def is_happy(n):
    slow, fast = n, n
    while True:
        slow = sum_of_squares(slow)
        fast = sum_of_squares(sum_of_squares(fast))
        if fast == 1:
            return True
        if slow == fast:
            return False


def sum_of_squares(n):
    sum = 0
    while n:
        digit = n % 10
        sum += digit ** 2
        n //= 10
    return sum

Big(O) Run-time Analysis

The run-time complexity is tricky to analyze precisely. In the worst case, we might have to iterate through several numbers before hitting a cycle or reaching 1. However, it's known that all numbers either become 1 or fall into a cycle with a limited number of elements. Therefore, we can consider it as O(log n) since the number of digits reduces substantially in each iteration.

Big(O) Space Usage Analysis

The space complexity for the naive solution is O(log n) because, in the worst case, we store numbers in a set until we find a cycle or arrive at 1. The number of unique numbers we encounter grows logarithmically with n.

For the optimal solution, space complexity is O(1) because we only use two variables slow and fast.

Edge Cases

  1. Input is 1: The algorithm should return true immediately.
  2. Large Input: The algorithm should handle large numbers without overflowing. Python handles large numbers automatically.
  3. Negative Input: The problem statement says the number will be a positive integer, but if we do get negative numbers, it would be better to take its absolute value, or just return false.
  4. Zero Input: If the number is zero, the algorithm should return false since the problem statement indicates 1 <= n.