DSAHashingCycle detection

Happy Number Visualizer

What is a Happy Number

Replace a number by the sum of the squares of its digits. If you reach 1 it is happy. If you see a number twice, you are in a cycle (unhappy numbers fall into a loop through 4). The hash set is the cycle detector — the same idea as detecting a loop in a linked list, but on integers.

  • Transform: n → Σ (digit²)
  • Seen set: insert before transforming. A repeat means “not happy”.
  • 1 is the only happy sink.

How this visualizer works

Start at 19: 19 → 82 → 68 → 100 → 1. Then try 2 and watch the set catch the cycle.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def isHappy(n):
2seen = set()
3while n != 1 and n not in seen:
4seen.add(n)
5n = sum(d*d for d in map(int, str(n)))
6return n == 1

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def isHappy(n):
2seen = set()
3while n != 1 and n not in seen:
4seen.add(n)
5n = sum(d*d for d in map(int, str(n)))
6return n == 1

complexity.md

OperationTime
Each transformO(#digits)
Until cycle / 1O(states)
SpaceO(states)

Python implementation

solution.py

1def isHappy(n):
2 seen = set()
3 while n != 1 and n not in seen:
4 seen.add(n)
5 n = sum(d * d for d in map(int, str(n)))
6 return n == 1