Level: Senior-Level
Round: Full Journey · Type: Coding · Difficulty: 4/10 · Duration: 60 min · Interviewer: Neutral
Topics: Algorithms, Hash Table, Math
Location: San Francisco Bay Area
Interview date: 2026-01-11
Coding Question: Determine if a number is a happy number based on the provided rules.
I was asked to implement a function to determine if a number is a "happy" number. A number is happy if, starting with the number, I repeatedly replace it with the sum of the squares of its digits until either the number becomes 1 (in which case it is happy) or it loops endlessly (in which case it is not happy). I need to return true if the number is happy, and false otherwise.
Constraints: The input n will be between 1 and 2^31 - 1.
Solution Approach: I used a HashSet to store every sum I calculated to detect if the sequence of numbers enters a loop.
` class Solution { public boolean isHappy(int n) { // Use a HashSet to track numbers we have already seen Set<Integer> seen = new HashSet<>();
// Loop until we reach 1 or detect a cycle
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = getSumOfSquares(n);
}
// If n is 1, it is a happy number
return n == 1;
}
// Helper function to calculate sum of squares of digits
private int getSumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
} `