Skip to content
LEETFLIX

Easy · happy-number cycle. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 202. Happy Number. The copyrighted prompt is on LeetCode. This page is a working happy-number cycle for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

n =
19

Output

true

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Sum of squared digits, detect a cycle

Replace n with the sum of the squares of its digits. If you hit 1, it is happy. If you see a number twice, you are in a loop — not happy.

The map of n → digit-square-sum is finite, so you either reach 1 or a cycle (the famous 4-loop).

Algorithm

  1. While n ≠ 1 and n is new, record it and replace it with the digit-square sum.
  2. Return whether you landed on 1.
Time
O(log n)
Space
O(log n)
Solution.py
class Solution:    def isHappy(self, n: int) -> bool:        seen: set[int] = set()        while n != 1 and n not in seen:            seen.add(n)            n = sum(int(d) ** 2 for d in str(n))        return n == 1
Watch this run

03

Interactive walkthrough

Playing “Sum of squared digits, detect a cycle”. Edit the input, hit Run, then scrub.

Approach: Sum of squared digits, detect a cycle

Loading animation…