Happy Number — LeetCode 202 Python Solution
- Problem
- #202
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits.
Example
- Input
- n = 19
- Output
- true
- Explanation
- 12 + 92 = 82
Python solution
class Solution:
def isHappy(self, n: int) -> bool:
vis = set()
while n != 1 and n not in vis:
vis.add(n)
x = 0
while n:
n, v = divmod(n, 10)
x += v * v
n = x
return n == 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 202. Happy Number is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On study lists
This problem is on NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 202. Happy Number?
- LeetCode 202. Happy Number is rated Easy on LeetCode.
- What is the time complexity of LeetCode 202. Happy Number?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 202. Happy Number?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 202. Happy Number cover?
- LeetCode 202. Happy Number is tagged Hash Table, Math and Two Pointers on LeetCode.