← DSA
EASY

Happy Number

PracticeNeetCode ↗LeetCode ↗

A number is "happy" if repeatedly replacing it with the sum of the squares of its digits eventually reaches 1. Determine whether a given number n is happy.

Example

Input n = 19
Output true

Key Pointers

Step-by-Step Analysis

  1. Create an empty set seen.
  2. Loop: if n == 1, return True.
  3. If n is already in seen, return False — a cycle was detected.
  4. Otherwise add n to seen, replace n with the sum of the squares of its digits, and repeat.

Complexity

Time: O(log n) per step, bounded number of distinct states — Space: O(log n)

Code

def isHappy(n: int) -> bool:
    seen = set()
    while n != 1:
        if n in seen:
            return False
        seen.add(n)
        n = sum(int(d) ** 2 for d in str(n))
    return True

Code Explanation

How the solution above works, piece by piece.

  1. Repeatedly replace n with the sum of the squares of its digits.
  2. If it reaches 1, the number is happy.
  3. Otherwise the sequence must eventually repeat a value (numbers quickly shrink below a few hundred), and a repeat means an endless loop. seen catches the first repeat → False.
  4. str(n) is a simple way to get the digits.
  5. Runs in effectively O(log n) steps; Floyd's cycle detection could replace the set to use O(1) memory.

Visual Walkthrough

Running it on n = 19:

Digit-square sequence from 19 to 119: 1² + 9² = 8282: 8² + 2² = 6868: 6² + 8² = 100100: 1² + 0² + 0² = 1reached 1 → happy → Trueif a number repeats before 1,the sequence loops forever → False
Each step replaces the number with the sum of the squares of its digits. The seen set detects a loop; here the sequence reaches 1 in four steps.
reached 1

Video Explanation

NeetCode — LeetCode 202