This is similar to LeetCode #141 - Linked List Cycle. We will reuse the algorithm from that problem to detect cycles.
- Create
slow
. It will move 1 step at a time. - Create
fast
. It will move 2 steps at a time. - We will keep generating numbers until either
- We generate
1
(we have a "happy number"), or slow
andfast
collide (we don't have a "happy number").
- We generate
class Solution {
public boolean isHappy(int n) {
if (n <= 0) {
return false;
}
int slow = n;
int fast = digitSquareSum(n); // setting fast to n would cause an immediate `slow == fast` collision
while (fast != 1 && slow != fast) {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
}
return fast == 1;
}
private int digitSquareSum(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}
O(1)
digitSquareSum()
will beO(log n)
- When (or if)
while (fast != 1 && slow != fast)
terminates asn
increases needs a mathematical proof that won't be necessary in an interview. - This gives us
O(log n) < time complexity < ???
O(1)