




Sponsored
Sponsored
The idea is to use a HashSet to track all numbers we've seen so far. If we encounter a number that we've seen before, it means we're in a cycle and the number is not happy. We keep replacing the number with the sum of the squares of its digits until we either reach 1 or the number starts repeating.
Time Complexity: O(log n), where n is the input number. Space Complexity: O(log n), as we store seen numbers.
1using System.Collections.Generic;
2
3public class Solution {
4    public bool IsHappy(int n) {
5        HashSet<int> seen = new HashSet<int>();
6        while (n != 1 && !seen.Contains(n)) {
7            seen.Add(n);
8            n = GetNext(n);
9        }
10        return n == 1;
11    }
12    
13    private int GetNext(int n) {
14        int totalSum = 0;
15        while (n > 0) {
16            int d = n % 10;
17            n /= 10;
18            totalSum += d * d;
19        }
20        return totalSum;
21    }
22}This C# solution uses a HashSet to memorize numbers as they are checked. If a number is revisited, a cycle is detected. The GetNext function calculates the sum of the squares of the digits.
This approach utilizes Floyd's Cycle-Finding Algorithm (also known as Tortoise and Hare). Instead of using a hash set, we can use two pointers: a slow pointer and a fast pointer. The slow pointer moves one step at a time, whereas the fast pointer moves two steps at a time. If they meet, it means the sequence is cyclic.
Time Complexity: O(log n). Space Complexity: O(1), since no extra space is used apart from variables.
1    
Java implementation of Floyd's cycle detection. The slow pointer goes step by step, while the fast pointer advances quickly. Meeting indicates a loop unless one hits 1.