A number is called happy if repeatedly replacing it with the sum of the squares of its digits eventually leads to 1.
So you do the same transformation again and again: split the number into digits, square each digit, add those squares, and use that new total as the next number. If the process reaches 1, return true. If it falls into a repeating loop that never reaches 1, return false.
For example, 19 is happy because its chain eventually reaches 1. But 2 is not happy because it keeps cycling through other values forever.
So the real task is not just doing the digit math once. It is detecting whether that repeated process ends at 1 or gets stuck in a loop.
The hash set approach is the most common and intuitive solution for this problem. An alternative approach uses Floyd's cycle detection algorithm with two pointers (like detecting a cycle in a linked list), which uses O(1) space instead of O(n). However, the hash set approach is simpler to understand and implement.
The problem is commonly asked in interviews to test understanding of hash sets for cycle detection. It also appears as an introduction to the concept of detecting infinite loops, which is relevant in many algorithmic contexts.
Example Input & Output
19 reaches 1 through repeated square-sum.
2 falls into a cycle not including 1.
1 is already happy.
Algorithm Flow
Solution Approach
Check if a number n is a happy number using a hash set to detect cycles. A happy number eventually reaches 1 when repeatedly replaced by the sum of the squares of its digits. If a cycle is detected (a number repeats), it is not happy.
Use a set to track numbers that have already been processed. Compute the sum of squared digits repeatedly. If we reach 1, return true. If we encounter a number already in the set, a cycle exists and we return false.
Time complexity is O(log n) for digit operations, space complexity is O(1) amortized.
Best Answers
import java.util.*;
class Solution {
public boolean solution(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
int sum = 0;
while (n > 0) { int d = n % 10; sum += d * d; n /= 10; }
n = sum;
}
return n == 1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
