hash_table.state
Input
Hash table
Current look-up
Match / window
Stored entry
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.
Interactive trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each transform | O(#digits) |
| Until cycle / 1 | O(states) |
| Space | O(states) |
Python implementation