LeetCode 202: Happy Number is an Easy hashmap problem. This Python walkthrough develops a cycle detection solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Hashmap |
| Reusable pattern | cycle detection |
| Complexity | O(log n) space per generated state and bounded practical time |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, repeatedly replace the number with the sum of squared digits. Stop at one or when a previously seen value proves a cycle. The invariant worth writing beside the code is: Every generated value is recorded once, so a repeat identifies a non-one cycle.
Step-by-step algorithm
- Identify the input state consumed by
isHappy(n)and initialize the data required by the cycle detection pattern. - Repeatedly replace the number with the sum of squared digits. Stop at one or when a previously seen value proves a cycle.
- After each update, verify the page’s central invariant: Every generated value is recorded once, so a repeat identifies a non-one cycle.
- Finish only after the boundary behavior is covered: Single-digit values other than one may still enter a longer cycle.
Python solution
class Solution:
def isHappy(self, n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(digit) ** 2 for digit in str(n))
return n == 1Reading the implementation
The main entry point is isHappy(n). The named working state includes seen, n; those variables make the cycle detection state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, repeatedly replace the number with the sum of squared digits. Stop at one or when a previously seen value proves a cycle.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Repeatedly replace the number with the sum of squared digits. Stop at one or when a previously seen value proves a cycle. Each update records the current item without invalidating earlier decisions; consequently, every generated value is recorded once, so a repeat identifies a non-one cycle.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(log n) space per generated state and bounded practical time. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().isHappy(19)Common mistakes and edge cases
- Problem-specific boundary: Single-digit values other than one may still enter a longer cycle.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that every generated value is recorded once, so a repeat identifies a non-one cycle.
Interview review checklist
- Explain why cycle detection matches the structure of this input.
- State the invariant in one sentence before tracing code: Every generated value is recorded once, so a repeat identifies a non-one cycle.
- Derive O(log n) space per generated state and bounded practical time from how many times each element or state is visited.
- Test the boundary explicitly: Single-digit values other than one may still enter a longer cycle.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 1. Two Sum · Next: 219. Contains Duplicate II