Happy Number (LeetCode 202): Solution and Explanation
Take a positive integer and repeatedly replace it with the sum of the squares of its digits. If the process eventually reaches 1, the number is happy; if it gets stuck in a loop that never includes 1, it is not.
Watch it run step by step
Try your own input and write the code →Intuition
Simulating the rule is easy. The hard part is knowing when to stop. If the sequence hits 1, you are done. But if the number is not happy, the sequence never hits 1, and a naive loop would run forever. You need a way to recognize that the process has given up.
The first useful fact is that the numbers cannot grow without bound. A number with d digits has a digit-square sum of at most 81 × d, which is far smaller than the number itself once it has four or more digits. For example, any value up to 9,999 maps to at most 324. So after a few steps every sequence is trapped among small numbers, and a sequence trapped in a finite set must eventually repeat a value.
Once a value repeats, the sequence is in a cycle and will repeat forever, because each step depends only on the current value. That means the question becomes: does the sequence reach 1 before it revisits any number? 1 maps to itself, so reaching 1 is just a cycle of length one.
A hash set answers that directly. Record each value as you produce it, and stop as soon as you reach 1 or a value you have already seen. If the loop ended on 1, the number is happy; if it ended on a repeat, it is not. This is the same cycle detection you would use on a linked list, only the next pointer is the digit-square function.
Approach: Cycle detection with a hash set
- Create an empty set
seen. - Loop while
n != 1andnis not inseen. - Add the current
ntoseen. - Replace
nwith the sum of the squares of its digits, computed by convertingnto a string and squaring each digit. - When the loop stops, return whether
n == 1. Any other exit means a repeated value, so the number is not happy.
Step-by-step example
n = 19
- 19 is not 1 and has not been seen, so add it. 1² + 9² = 82.
- Add 82. 8² + 2² = 64 + 4 = 68.
- Add 68. 6² + 8² = 36 + 64 = 100.
- Add 100. 1² + 0² + 0² = 1.
nis now 1, so the loop stops and the function returns true. 19 is a happy number.
Code: Python, Java, C++
1class Solution:
2 def isHappy(self, n: int) -> bool:
3 seen = set()
4
5 while n != 1 and n not in seen:
6 seen.add(n)
7 n = sum(int(d) ** 2 for d in str(n))
8
9 return n == 11class Solution {
2 public boolean isHappy(int n) {
3 Set<Integer> seen = new HashSet<>();
4
5 while (n != 1 && !seen.contains(n)) {
6 seen.add(n);
7 int sum = 0;
8 while (n > 0) {
9 int digit = n % 10;
10 sum += digit * digit;
11 n /= 10;
12 }
13 n = sum;
14 }
15
16 return n == 1;
17 }
18}1class Solution {
2public:
3 bool isHappy(int n) {
4 unordered_set<int> seen;
5
6 while (n != 1 && seen.find(n) == seen.end()) {
7 seen.insert(n);
8 int sum = 0;
9 while (n > 0) {
10 int digit = n % 10;
11 sum += digit * digit;
12 n /= 10;
13 }
14 n = sum;
15 }
16
17 return n == 1;
18 }
19};Time and space complexity
O(log n)
The first step costs time proportional to the number of digits of n, which is O(log n). After that the values stay below a few hundred, so the number of further steps and their cost are bounded by a constant.
O(log n)
The set stores every value in the sequence, which is a handful of values from the first steps plus a bounded number of small values, so it is dominated by the same O(log n) term.
Other approaches
Floyd's tortoise and hare (time O(log n), space O(1))
Run two copies of the sequence, one taking one step at a time and one taking two. If the fast one reaches 1, the number is happy; if the two meet elsewhere, there is a cycle without 1. It needs no set at all.
Known cycle check (time O(log n), space O(1))
Every unhappy number eventually enters the same cycle, which contains 4. So you can loop until n is 1 or 4 and return whether it is 1. It is constant space and very short, but relies on a mathematical fact you need to trust or prove.
Common mistakes
- Looping with only
while n != 1. For an unhappy number such as 2, that loop never ends. - Adding
ntoseenand then checking membership before computing the next value. Every number is found in the set right after being added, so the function reports a cycle on the first step. - Squaring the whole number or summing the digits without squaring them, which follows a completely different sequence.
- Returning false the moment the value grows larger than before. Values can rise temporarily (for example 7 becomes 49) and still end at 1.
Frequently asked questions
Why does the Happy Number process always end in a cycle?
The digit-square sum of a large number is much smaller than the number itself, so every sequence quickly drops into a small range. In a finite range some value must repeat, and from then on the sequence cycles. Happy numbers just cycle at 1.
Can Happy Number be solved without a hash set?
Yes. Floyd's slow and fast pointers detect the cycle in O(1) space. Another option is to stop at 1 or 4, since every unhappy number enters a cycle that includes 4.
What is the time complexity of Happy Number?
O(log n). Computing the first digit-square sum takes time proportional to the number of digits, and the remaining steps are bounded by a constant because the values stay small.