algoadvance

Leetcode 202. Happy Number

Problem Statement

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

A happy number is a number defined by the following process:

Return true if n is a happy number and false if not.

Clarifying Questions

  1. Range of Input: What is the range of input values (e.g., positive integers only)?
    • Assumption: The input will be a positive integer.
  2. Edge Cases: Do we need to handle extremely large numbers?
    • For typical usage, standard constraints on integers in C++ should suffice.

Strategy

  1. Step-by-Step Process:
    • Calculate the sum of squares of the digits.
    • Use a set to track the numbers we have seen to detect cycles.
    • Repeat until we encounter 1 (happy number) or detect a cycle (unhappy number).
  2. Functions Needed:
    • A helper function to compute the sum of squares of digits.
    • A main function to implement the cycle detection using a set.

Code

#include <iostream>
#include <unordered_set>

class Solution {
public:
    bool isHappy(int n) {
        std::unordered_set<int> seen;
        
        while (n != 1 && seen.find(n) == seen.end()) {
            seen.insert(n);
            n = getNext(n);
        }
        
        return n == 1;
    }
    
private:
    int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int digit = n % 10;
            n = n / 10;
            totalSum += digit * digit;
        }
        return totalSum;
    }
};

int main() {
    Solution solution;
    int n = 19;  // Example input
    std::cout << (solution.isHappy(n) ? "True" : "False") << std::endl;
    return 0;
}

Explanation

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI