KatInterview

202. Happy Number

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem defines a "happy number" through an iterative process: starting with a positive integer, replace it with the sum of the squares of its digits. This process is repeated. If the number becomes 1, it's a happy number. If it enters a cycle that doesn't include 1, it's not. Our task is to determine if a given number n is happy.

Solution

Happy Number in Python

class Solution:
    def isHappy(self, n: int) -> bool:

        def get_next(num: int) -> int:
            """Helper function to calculate the sum of the squares of the digits."""
            total_sum = 0
            while num > 0:
                num, digit = divmod(num, 10)
                total_sum += digit ** 2
            return total_sum

        # Use Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
        slow_runner = n
        fast_runner = get_next(n)

        # The loop terminates if a cycle is detected (slow_runner == fast_runner)
        # or if we reach the number 1.
        while fast_runner != 1 and slow_runner != fast_runner:
            slow_runner = get_next(slow_runner)          # Move one step
            fast_runner = get_next(get_next(fast_runner)) # Move two steps
        
        # If the process ends at 1, the number is happy.
        return fast_runner == 1

Happy Number in Java

class Solution {
    // Helper method to calculate the sum of the squares of the digits of a number.
    private int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10; // Get the last digit
            n = n / 10;     // Remove the last digit
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy(int n) {
        // Use Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
        int slowRunner = n;
        int fastRunner = getNext(n);

        // The loop terminates if a cycle is detected (slowRunner == fastRunner)
        // or if we reach the number 1.
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);          // Move one step
            fastRunner = getNext(getNext(fastRunner)); // Move two steps
        }

        // If the process ends at 1, the number is happy.
        return fastRunner == 1;
    }
}

Happy Number in C++

class Solution {
private:
    // Helper function to calculate the sum of the squares of the digits of a number.
    int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;  // Get the last digit
            n = n / 10;      // Remove the last digit
            totalSum += d * d;
        }
        return totalSum;
    }

public:
    bool isHappy(int n) {
        // Use Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
        int slowRunner = n;
        int fastRunner = getNext(n);

        // The loop terminates if a cycle is detected (slowRunner == fastRunner)
        // or if we reach the number 1.
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);          // Move one step
            fastRunner = getNext(getNext(fastRunner)); // Move two steps
        }

        // If the process ends at 1, the number is happy.
        return fastRunner == 1;
    }
};

Happy Number in TypeScript

function isHappy(n: number): boolean {
    // Helper function to calculate the sum of the squares of the digits of a number.
    const getNext = (num: number): number => {
        let totalSum = 0;
        while (num > 0) {
            const digit = num % 10;      // Get the last digit
            num = Math.floor(num / 10);  // Remove the last digit
            totalSum += digit * digit;
        }
        return totalSum;
    };

    // Use Floyd's Cycle-Finding Algorithm (Tortoise and Hare).
    let slowRunner = n;
    let fastRunner = getNext(n);

    // The loop terminates if a cycle is detected (slowRunner === fastRunner)
    // or if we reach the number 1.
    while (fastRunner !== 1 && slowRunner !== fastRunner) {
        slowRunner = getNext(slowRunner);          // Move one step
        fastRunner = getNext(getNext(fastRunner)); // Move two steps
    }

    // If the process ends at 1, the number is happy.
    return fastRunner === 1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.