202. Happy Number

Question:

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 <= 2^31 - 1

Solution:

  • Visualize each new n that you will calculate (on summing the squares of the digits of previous n) as a LinkedList, where there is a possibility of n values repeating.
  • So, one can solve this using HashSet or the Hare Tortoise Algorithm of cycle detection.
  • Keep fast and slow variables. Slow will store the next such n. Fast will store the next to next such n.
  • If fast reaches 1, then we have concluded that original n was a happy number.
  • If fast equals slow anywhere (and is not 1) in the while loop, we have found a cycle, and hence concluded that there is no way for original n to be a happy number unless the original number was 1 itself.
  • This statement: if(fast == 1) return true; makes our code just a little bit faster. Else, it can be omitted.

Code:


class Solution {
    public boolean isHappy(int n) {

        int slow = n, fast = square(n);

        while(slow != fast){

            slow = square(slow);
            fast = square(square(fast));

            if(fast == 1) return true;
        }

        if(slow == 1) return true;
        return false;
    }

    static int square(int n){

        int prod = 0, digit;

        while(n > 0){
            digit  = n % 10;
            prod += (int)Math.pow(digit, 2);
            n = n / 10;
        }

        return prod;
    }
}

Complexity:

  • Time: O(logN) - cost of calculating the next N for 2 different runners: O(2*logN) = O(logN)
  • Space: O(1)