Happy Number
An easy Math problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Math
- Sheets
- 2
- Core for
- 13 roles
- Platform
- LeetCode
The problem
Write an algorithm to determine if a number n is happy. A happy number is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy.
Example 1
- Input
- n = 19
- Output
- true
- Why
- 19 -> 1^2+9^2=82 -> 8^2+2^2=68 -> 6^2+8^2=100 -> 1^2+0^2+0^2=1. The process reaches 1, so 19 is a happy number.
Example 2
- Input
- n = 2
- Output
- false
- Why
- 2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4... enters a cycle that does not include 1, so 2 is not happy.
Constraints
- 1 <= n <= 2^31 - 1
How to think about it
Updated 2026-09-09The sum of squares of digits of any 32-bit integer quickly collapses into a bounded set below 243. Because the domain is finite and deterministic, the sequence must either reach 1 or enter a closed loop, making cycle detection the exact mathematical match.
Approaches, worst first
Hash set cycle detection
time O(log n) · space O(log n)
Compute the digit square sum iteratively, inserting each seen number into a hash set. If the value hits 1, it is happy; if it matches an element already in the set, a cycle is found.
Floyd cycle-finding algorithmWrite this one
time O(log n) · space O(1)
Advance two pointers: slow steps forward one digit-square sum at a time while fast steps twice. If fast reaches 1, the number is happy; if slow and fast collide before 1, it is stuck in a non-happy cycle, all without allocating a hash set.
Where people lose marks · 2
- Failing to terminate on numbers that loop indefinitely, causing an infinite loop when cycle detection is omitted.
- Incorrect digit extraction logic that misses the last remaining digit when stripping with n / 10.
The theory behind it
Math — the ground this problem stands on. All Math problems
What Math is
Algorithmic math is the application of number properties, modular arithmetic, and geometric patterns to compute results without simulating every step. Rather than filling memory buffers with millions of simulated counters or walking endless loops, mathematical formulation uses identities like prime factorization, digit extraction, and greatest common divisors to jump directly to target answers through closed-form rules.
When to reach for it
Reach for mathematical techniques when problem bounds are massive, such as constraints reaching ten to the eighteenth power where simulation is impossible. Strong prompts mention prime generation, greatest common divisor calculations, modular inverses, fast exponentiation, digit reversals, or combinatorial arrangements. If brute-force counting produces memory overflow or time limit exceeded warnings, algebraic reorganization is the intended path.
How the pattern works
Focus on numeric constraints and potential overflows before writing expressions. Break numbers into constituent digits using modulo ten to peel least significant figures and integer division to shrink scale. For divisibility, apply Euclid's remainder theorem repeatedly until remainder drops to zero. Apply modulo arithmetic at every intermediate addition and multiplication stage rather than once at the end, preventing values from spilling beyond standard numeric register limits.
What each operation costs
| Operation | Time |
|---|---|
| greatest common divisor via euclidean algorithm | O(log(min(a, b))) |
| modular exponentiation by repeated squaring | O(log n) |
| prime sieve of eratosthenes up to n | O(n log log n) |
What usually goes wrong with Math
- Allowing 32-bit signed integer overflow during intermediate multiplications before modulo reduction is applied, producing negative or truncated results.
- Failing to handle negative inputs in modulo arithmetic, producing negative remainders in languages that implement truncated rather than floored division.
- Dividing by zero when the denominator or remainder becomes zero at unexpected edge boundary values like empty sets or singletons.
Which roles need this problem
Math is a core topic for these 13 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 7 more roles, including Security Engineer, Performance Engineer, Site Reliability Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Math problems
Problem set and role mapping as of .