Search⌘ K
AI Features

Solution: Happy Number

Explore the fast and slow pointers technique to determine if a number is a happy number by detecting cycles in the sequence formed from the sum of squared digits. Understand how to implement this approach efficiently, analyze its time and space complexity, and differentiate between naive and optimal solutions for cycle detection in iterative processes.

Statement

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

We use the following process to check if a given number is a happy number:

  • Starting with the given number nn, replace the number with the sum of the squares of its digits.
  • Repeat the process until:
    • The number equals 11, which will depict that the given number nn is a happy number.
    • It enters a cycle, which will depict that the given number nn is not a happy number.

Return TRUE if nn is a happy number, and FALSE if not.

Constraints

  • 11 \leq nn 2311\leq 2^{31} - 1

Solution

So far, you have probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive approach

The brute force approach is to repeatedly calculate the squared sum of digits of the input number and store the computed sum in a hash set. For every calculation, we check if the sum is already present in the set. If yes, we've detected a cycle and should return FALSE. Otherwise, we add it to our hash set and continue further. If our sum converges to 11, we've found a happy number.

While this approach works well for small numbers, we might have to perform several computations for larger numbers to get the required result. So, it might get infeasible for such cases. The time complexity is O(logn)O(\log n) because finding the next value requires processing each digit, which takes O(logn)O(\log n) ...