Back to DashboardView Problem Source
Happy Number
MediumProblem Statement
Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to the number 1. All other (not-happy) numbers will never reach 1. Instead, they will be stuck in a cycle of numbers that does not include 1.
Given a positive number n, return true if it is a happy number otherwise return false.
Examples
Example 1:
- Input:
23 - Output:
true
Approach 1 Slow Fast Pointers:
class Solution {
public boolean isHappy(int n) {
var slow = n;
var fast = n;
while (slow != 1 && fast != 1) {
slow = findSquare(slow);
fast = findSquare(findSquare(fast));
if (slow != 1 && fast != 1 && fast == slow) {
return false;
}
}
return true;
}
int findSquare(int n) {
var square = 0;
while (n > 0) {
var rem = n % 10;
n = n / 10;
square += rem * rem;
}
return square;
}
}
Status
Solved
Complexity
Time
O(n)Space
O(1)Tags
Linked ListSlow Fast Pointers
Date
2026-02-10