Solution: Happy Number

Let's solve the Happy Number problem using the Fast and slow pointers pattern

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 of this approach is O(logn)O( \log n). The space complexity is O(logn)O(\log n) ...

Access this course and 1400+ top-rated courses and projects.