DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Understanding Happy Number (LeetCode 202) – HashSet + Cycle Detection

Today I solved a classic problem that looks simple but teaches an important concept: cycle detection using a HashSet.

Problem Summary

A number is called a Happy Number.If replace the number with the sum of squares of its digits.Repeat the process if it eventually becomes 1, it is happy.If it enters a loop and never reaches 1, it is not happy.

Example

Input:-> n = 19

Process:

1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1

Since it reaches 1, the answer is true.

Key Idea

1) The tricky part is:

-> Some numbers fall into an infinite cycle.

2) So how do we detect that?

3) We store already seen numbers inside a HashSet.

4) If a number repeats → we are in a cycle → return false.

C++ Implementation

class Solution {
private:
    int SqrtOfSum(int n){
        int sum = 0;
        while(n > 0){
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return sum;
    }

public:
    bool isHappy(int n) {
        unordered_set<int> ust;

        while(n != 1 && ust.find(n) == ust.end()){
            ust.insert(n);
            n = SqrtOfSum(n);
        }

        return n == 1;
    }
};

Enter fullscreen mode Exit fullscreen mode

Complexity

Time Complexity: O(log n) (digit processing repeatedly)
Space Complexity: O(log n) (numbers stored in set)

What I Learned

  1. How to break a number into digits using % 10 and / 10.
  2. How to detect cycles using unordered_set.
  3. Not all loops are obvious — sometimes you must detect them manually.
  4. Simple problem, powerful concept.

Top comments (1)

Collapse
 
charles_kumar_30654e10958 profile image
Charles Kumar

Simple problem, powerful concept. yes, Indeed

In today's fast paced AI world, this happy numbers is applied in our day to day life

Financial Fraud Detection

  • Money Laundering Loops: Banks model transactions as directed graphs to identify instances where funds circulate through multiple accounts before returning to the source.

Computer Networking

  • Routing Loops: Detecting if a data packet is being passed in a circle between routers, which can crash a network.
  • Deadlock Detection: Identifying cyclic dependencies in distributed systems where multiple processes are stuck waiting for each other. [1]

Software Development & Systems

  • Garbage Collection: Identifying "cyclic references" in memory (where two objects point to each other) so they can be properly cleared by engines like the Java Garbage Collector.
  • Infinite Loop Protection: Compilers use this logic to detect potential infinite loops in code execution. [2]

Cryptography & Security

  • Hash Collisions: Identifying if different inputs produce the same output (a cycle), used to test the strength of cryptographic hash functions.
  • Random Number Generation: Testing the quality of pseudorandom number generators by ensuring they don’t repeat a sequence too quickly.

Bioinformatics

  • Sequence Analysis: Analyzing DNA sequences to identify repeat patterns or cyclic structures in protein simulations.

Implementation Comparison

Feature HashSet Method Floyd’s (Tortoise & Hare)
Logic Stores every "seen" number in a set. Uses two pointers moving at different speeds.
Space O(N) — uses more memory as the sequence grows. O(1) — extremely memory efficient.
Best For Small sequences or when you need a history of values. Large datasets or memory-constrained environments.