Taro Logo

Happy Number

#200 Most AskedEasy
Topics:
ArraysRecursionTwo Pointers

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.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible value for the input integer `n`, and could it exceed standard integer limits?
  2. Are we guaranteed that the input `n` will always be a positive integer as stated, or do we need to handle edge cases like zero or negative numbers?
  3. Since the process can loop endlessly, is there an upper bound on the number of iterations we should perform, or is cycle detection (like Floyd's Cycle-Finding algorithm) expected?
  4. Should the function return a boolean `true` or `false`, or are there any specific requirements regarding returning the intermediate sequence of numbers?
  5. If the number falls into the well-known non-happy cycle (which includes 4), is it sufficient to just detect that we've hit a number we've already seen?

Brute Force Solution

Approach

Imagine you start with a number and repeatedly replace it with the sum of the squares of its digits, hoping to eventually reach the number one. The brute force approach simply follows this exact process step by step, hoping it stops at one or keeps running forever.

Here's how the algorithm would work step-by-step:

  1. Take your starting number and break it apart into its individual digits.
  2. Square each of those digits and add all the resulting values together to get a brand new number.
  3. Take this new number and repeat the exact same process of breaking it into digits, squaring them, and adding them up.
  4. Keep repeating this transformation process over and over again, generating a sequence of new numbers.
  5. As you generate each new number, check to see if it has successfully become the number one, which means you have found a happy number.
  6. If it becomes one, stop and celebrate because your mission is complete.
  7. However, since some numbers will get trapped in an endless repeating cycle of numbers that never reaches one, you need a way to watch out for repeating patterns.
  8. Keep a mental list of every single number you have already generated during this process.
  9. Before moving to the next step, check if the number you just calculated is already on your list of previously seen numbers.
  10. If you see a number repeat, it means you are stuck in an endless loop and will never reach one, so you must stop and conclude the number is not happy.

Code Implementation

def is_happy(starting_number):
    seen_numbers = set()
    
    current_number = starting_number
    
    while current_number != 1:
        # We maintain a history to detect infinite loops since unhappy numbers always cycle
        if current_number in seen_numbers:
            return False
            
        seen_numbers.add(current_number)
        
        next_sum_of_squares = 0
        
        number_to_process = current_number
        
        while number_to_process > 0:
            digit = number_to_process % 10
            next_sum_of_squares += digit * digit
            number_to_process //= 10
            
        current_number = next_sum_of_squares
        
    # Reaching one means the transformation process successfully completed its mission
    return True

Big(O) Analysis

Time Complexity
O(log n) – The time complexity is driven by the number of digit-square transformations and the number of digits in the integer n. Extracting the digits of a number takes logarithmic time relative to the value of n, specifically proportional to the number of digits log base 10 of n. Because the sequence of sums is bounded by a small constant for any integer, the cycle detection loop runs a constant maximum number of iterations. Combining these factors yields approximately O(log n) operations, which simplifies to O(log n).
Space Complexity
O(log N) – To detect endless loops as described in the steps, we maintain a hash set acting as the mental list of previously seen numbers. The auxiliary space required by this hash set is determined by the number of unique intermediate values generated before reaching 1 or detecting a cycle. Because the value of the numbers rapidly shrinks and stays bounded, the number of distinct digits and subsequent sequence values scale logarithmically with the magnitude of the input number N. Therefore, the extra memory used by the hash set grows proportionally to the log of the input size.

Optimal Solution

Approach

To determine if a number is happy, we repeatedly replace it with the sum of the squares of its digits until we either reach the goal of one or get stuck in a repeating loop. The optimal strategy relies on a classic chase game between two moving paces to detect if we are trapped in a circle without needing to remember every number we have ever visited.

Here's how the algorithm would work step-by-step:

  1. Take your starting number and calculate a new value by squaring each of its digits and adding those squares together.
  2. Imagine two runners starting at the same place, but one moves forward by taking two transformation steps at a time while the other takes only one.
  3. Keep applying the transformation process to both runners repeatedly.
  4. If the faster runner ever lands on the target success value of one, celebrate because you have found a happy number.
  5. If the faster runner eventually catches up to the slower runner at some other number that is not one, it means they are running in a permanent circle and you are stuck in an endless loop, proving the number is not happy.
  6. Repeat the movement process until one of these two stopping conditions occurs.

Code Implementation

class Solution:
    def get_next_number(self, current_number):
        total_sum_squares = 0
        while current_number > 0:
            current_digit = current_number % 10
            total_sum_squares += current_digit ** 2
            current_number //= 10
        return total_sum_squares

    def isHappy(self, initial_number: int) -> bool:
        # Tortoise and hare pointers allow cycle detection without extra memory.
        slow_runner = initial_number
        fast_runner = self.get_next_number(initial_number)

        # Moving pointers at different speeds guarantees they meet if a cycle exists.
        while fast_runner != 1 and slow_runner != fast_runner:
            slow_runner = self.get_next_number(slow_runner)
            fast_runner = self.get_next_number(self.get_next_number(fast_runner))

        # Reaching one means all digits squared eventually reduced to the success target.
        return fast_runner == 1

Big(O) Analysis

Time Complexity
O(log n) – The time complexity is driven by the number of digit extraction and squaring operations required to transform the input number n. In each step, the number of digits of n is roughly proportional to log base 10 of n, meaning each transformation takes O(log n) time. Because the sequence of numbers generated by non-happy numbers is bounded by a small constant range and happy numbers converge quickly, the cycle detection takes a constant number of steps on average. Thus, the total operations approximate O(log n) time due to the shrinking size of the digits processed at each step.
Space Complexity
O(1) – The algorithm relies on the Tortoise and Hare cycle detection technique using only a few primitive integer variables to track the current values of the slow and fast runners. Because no auxiliary data structures like hash sets or arrays grow dynamically with the input, the extra memory usage remains entirely constant. Specifically, the space complexity is O(1) auxiliary space regardless of the magnitude of the starting number.

Edge Cases

Input is 1
How to Handle:
The algorithm should immediately return true since 1 is defined as a happy number.
Input enters a non-happy cycle (such as starting with 4)
How to Handle:
A cycle detection mechanism like a HashSet or Fast and Slow pointers prevents infinite loops by catching previously seen sums.
Numbers with trailing zeros like 10 or 100
How to Handle:
Digit extraction using modulo and division correctly isolates non-zero digits and includes zero squares in the sum.
Maximum 32-bit signed integer inputs
How to Handle:
Since the sum of squares of digits for any large integer quickly reduces to a much smaller number below 810, integer overflow is not an issue.
Inputs consisting of all 9s such as 99
How to Handle:
The algorithm correctly computes the sum of squares for each digit and transitions to the next step in the sequence.
0/245 completed