🧠
Mathematical Insight with Known Cycle Detection
💡 This approach uses known facts about cycles in happy numbers to shortcut detection, useful for optimization and demonstrating domain knowledge.
Intuition
All unhappy numbers eventually enter a known cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. If the sequence hits any number in this cycle, it is not happy.
Algorithm
- Define a set of known cycle numbers for unhappy sequences.
- Iterate computing sum of squares of digits.
- If the number becomes 1, return true.
- If the number is in the known cycle set, return false.
💡 This approach trades memory for speed by using a fixed set of cycle numbers.
def isHappy(n: int) -> bool:
cycle_set = {4, 16, 37, 58, 89, 145, 42, 20}
def get_next(number):
total_sum = 0
while number > 0:
digit = number % 10
total_sum += digit * digit
number //= 10
return total_sum
while n != 1 and n not in cycle_set:
n = get_next(n)
return n == 1
# Driver code
if __name__ == '__main__':
print(isHappy(19)) # Expected: True
print(isHappy(2)) # Expected: False
Line Notes
cycle_set = {4, 16, 37, 58, 89, 145, 42, 20}Known unhappy cycle numbers to detect loops quickly
while n != 1 and n not in cycle_set:Loop until happy or known cycle detected
def get_next(number):Helper to compute sum of squares of digits
return n == 1Return true if happy, false if cycle detected
import java.util.Set;
import java.util.HashSet;
public class HappyNumber {
private static final Set<Integer> cycleSet = new HashSet<>();
static {
cycleSet.add(4); cycleSet.add(16); cycleSet.add(37); cycleSet.add(58);
cycleSet.add(89); cycleSet.add(145); cycleSet.add(42); cycleSet.add(20);
}
public static boolean isHappy(int n) {
while (n != 1 && !cycleSet.contains(n)) {
n = getNext(n);
}
return n == 1;
}
private static int getNext(int number) {
int totalSum = 0;
while (number > 0) {
int digit = number % 10;
totalSum += digit * digit;
number /= 10;
}
return totalSum;
}
public static void main(String[] args) {
System.out.println(isHappy(19)); // true
System.out.println(isHappy(2)); // false
}
}
Line Notes
private static final Set<Integer> cycleSet = new HashSet<>();Store known unhappy cycle numbers
while (n != 1 && !cycleSet.contains(n)) {Loop until happy or known cycle detected
cycleSet.add(4);Initialize cycle set with known cycle numbers
return n == 1;Return true if happy, false otherwise
#include <iostream>
#include <unordered_set>
using namespace std;
bool isHappy(int n) {
static unordered_set<int> cycleSet = {4,16,37,58,89,145,42,20};
auto getNext = [](int number) {
int totalSum = 0;
while (number > 0) {
int digit = number % 10;
totalSum += digit * digit;
number /= 10;
}
return totalSum;
};
while (n != 1 && cycleSet.find(n) == cycleSet.end()) {
n = getNext(n);
}
return n == 1;
}
int main() {
cout << boolalpha << isHappy(19) << endl; // true
cout << boolalpha << isHappy(2) << endl; // false
return 0;
}
Line Notes
static unordered_set<int> cycleSet = {4,16,37,58,89,145,42,20};Known cycle numbers stored statically
while (n != 1 && cycleSet.find(n) == cycleSet.end()) {Loop until happy or cycle detected
auto getNext = [](int number) {Lambda to compute sum of squares
return n == 1;Return true if happy, false otherwise
const cycleSet = new Set([4,16,37,58,89,145,42,20]);
function getNext(number) {
let totalSum = 0;
while (number > 0) {
let digit = number % 10;
totalSum += digit * digit;
number = Math.floor(number / 10);
}
return totalSum;
}
function isHappy(n) {
while (n !== 1 && !cycleSet.has(n)) {
n = getNext(n);
}
return n === 1;
}
// Test cases
console.log(isHappy(19)); // true
console.log(isHappy(2)); // false
Line Notes
const cycleSet = new Set([4,16,37,58,89,145,42,20]);Known unhappy cycle numbers for quick detection
while (n !== 1 && !cycleSet.has(n)) {Loop until happy or cycle detected
function getNext(number) {Helper to compute sum of squares
return n === 1;Return true if happy, false otherwise
TimeO(k * log n) with small constant due to early cycle detection
SpaceO(1) constant space
Checking membership in a small fixed set is O(1), speeding up cycle detection.
💡 This approach is a practical optimization that leverages known math facts to shortcut cycle detection.
Interview Verdict: Accepted
This approach is efficient and shows domain knowledge, which can impress interviewers.