Happy Number — LeetCode 202 Python Solution

EasyHash TableMathTwo Pointers
Problem
#202
Reading time
2 min

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

Python
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 == 1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview