Search⌘ K
AI Features

Solution: Happy Number

Explore how to identify happy numbers by using the fast and slow pointers technique to detect cycles efficiently. This lesson guides you through implementing a helper function to compute the sum of squared digits and applying pointer advancements to determine if the sequence ends in 1 or forms a cycle. You will understand the algorithm's logic and its time and space complexity implications.

Statement

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

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

  • Starting with the given number numnum, 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 numnum is a happy number.
    • It enters a cycle, which will depict that the given number numnum is not a happy number.

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

Constraints

  • 11 \leq num 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) ...