Happy Number
Easy
MathHash SetCycle Detection
Problem
A number is "happy" if repeatedly summing the squares of its digits eventually reaches 1. Otherwise it cycles. Return true iff n is happy.
Example 1
Input: n = 19
Output: true
Explain: 19 → 82 → 68 → 100 → 1
Example 2
Input: n = 2
Output: false
Constraints
- 1 ≤ n ≤ 2³¹ − 1
Approach — Hashing & Counting
This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class Solution:
def isHappy(self, n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return n == 1
Java
import java.util.*;
class Solution {
public boolean isHappy(int n) {
// Hash-set cycle detection: the digit-square sequence either
// reaches 1 or revisits a number it has already seen (a cycle).
Set<Integer> seen = new HashSet<>();
while (n != 1 && seen.add(n)) n = next(n);
return n == 1;
}
private int next(int n) {
int s = 0;
while (n > 0) { int d = n % 10; s += d * d; n /= 10; }
return s;
}
// O(1)-space alternative (the Fast & Slow track's approach):
// int slow = n, fast = next(n);
// while (fast != 1 && slow != fast) {
// slow = next(slow);
// fast = next(next(fast));
// }
// return fast == 1;
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Happy Number interactively → ← All solutions