Happy Number solution explained
To check whether a number is happy, keep replacing it with the sum of the squares of its digits and stop when you reach 1 (happy) or a value you have seen before (a loop, so not happy). A set of seen values works; Floyd's fast and slow pointers find the loop with O(1) extra memory. Each step costs O(number of digits) and the values quickly drop below a few hundred, so the Happy Number solution effectively runs in O(log n) time.
By Evin JohnPublished 7 min read
The task, restated
Take a positive integer. Split it into its digits, square each, and add the squares. That sum is the next number. Repeat. If the process ever lands on 1, it stays there (1 squared is 1), and the starting number is called happy. Otherwise it is unhappy. Write a function that returns true or false for a given starting number.
| Start | Chain | Happy? |
|---|---|---|
| 7 | 7 → 49 → 97 → 130 → 10 → 1 | Yes |
| 23 | 23 → 13 → 10 → 1 | Yes |
| 2 | 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ... | No, loops back to 4 |
| 1 | 1 | Yes, already there |
Two quick questions: is the input always a positive integer, and how large can it be? The approach does not change for very large inputs, but the answer to "why does this terminate?" depends on the numbers shrinking, which is worth stating.
Why the process cannot run forever
This is the part interviewers like to hear. A number with d digits produces a next value of at most 81·d, since each digit contributes at most 9 squared. For any number with four or more digits, 81·d is far smaller than the number itself, so the sequence drops quickly. Once it is below 1,000, the next value is at most 243 (the sum for 999), and it stays in that small range. A sequence confined to a finite set of values must eventually repeat one. So it either reaches 1 or enters a loop, and our test of every start up to 19,999 found only one loop: 4, 16, 37, 58, 89, 145, 42, 20 and back to 4.
How interviewers use it
Happy Number is a short warm-up that hides a real question: the moment you see "repeat until it stops", how do you know it stops, and how do you detect when it does not? Interviewers use it to see whether you reach for a seen-set naturally and whether you can then recognize the same structure as a linked list with a cycle. The constant-memory follow-up is the main event.
- Do it without a set. Fast and slow pointers, shown below.
- Return the length of the loop, or where it starts. After the pointers meet, the standard Floyd steps find both.
- Change the rule, such as cubes of digits. The same cycle detection works, but the bound argument has to be redone.
- Answer many queries. Precompute happiness for every value up to 243 once; any input reduces into that range within a few steps.
Brute force: remember every value you have seen
Keep a set. Before each step, if the current value is 1, return true; if it is already in the set, you are in a loop, return false; otherwise add it and move on. The number of steps is small because of the bound above, so this is already fast. Its only cost is memory for the set.
def digit_square_sum(n):
total = 0
while n:
n, d = divmod(n, 10)
total += d * d
return total
def is_happy_set(n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = digit_square_sum(n)
return n == 1Constant memory: a fast and a slow pointer
Think of each number as a node whose only outgoing arrow points to its digit-square sum. Starting from n, you follow a path that ends in a loop. If 1 is reachable, the loop is 1 pointing to itself. Run two walkers: slow takes one step at a time, fast takes two. If there is a loop, fast catches slow inside it. Then check where they met: if the loop is the 1-to-1 loop, the number is happy. You can also stop early as soon as fast reaches 1.
def is_happy(n):
slow, fast = n, digit_square_sum(n)
while fast != 1 and slow != fast:
slow = digit_square_sum(slow)
fast = digit_square_sum(digit_square_sum(fast))
return fast == 1function digitSquareSum(n) {
let total = 0;
while (n > 0) {
const d = n % 10;
total += d * d;
n = Math.floor(n / 10);
}
return total;
}
function isHappy(n) {
let slow = n, fast = digitSquareSum(n);
while (fast !== 1 && slow !== fast) {
slow = digitSquareSum(slow);
fast = digitSquareSum(digitSquareSum(fast));
}
return fast === 1;
}Starting fast one step ahead avoids the loop condition being true before any step is taken. If you start both at n, use a do-while style loop instead.
Time and space
| Version | Time | Extra space |
|---|---|---|
| Seen set | O(log n) for the first steps, then a bounded number of steps on values ≤ 243 | O(length of the chain), bounded by a small constant after the first steps |
| Fast and slow pointers | Same order, about three times the digit-sum calls | O(1) |
| Precomputed table up to 243 | O(log n) per query | O(1) per query, one table |
The first digit-square sum of n costs O(log n) because n has about log n digits. Every later value is small, so the remaining work is bounded. Saying "O(log n), dominated by the first step" is a good summary.
Edge cases
- n = 1, which is happy without a single step.
- Single digits: only 1 and 7 are happy among 1 to 9.
- Numbers that reach 4, the entry point of the only unhappy loop we found.
- Large inputs: one step shrinks them to a few hundred or less.
- Zero or negative input, which the usual version excludes; ask before handling it.
Mistakes to avoid
- Looping until the value hits 1 with no loop check, which never ends for unhappy numbers.
- In JavaScript, dividing without Math.floor, so the digit loop runs on fractions.
- Starting fast and slow at the same value with a while loop that checks equality first, which exits immediately.
- Hardcoding the unhappy loop's values without explaining where they come from.
- Converting to a string for every step when asked about efficiency; it works, but say what it costs.
How to explain it out loud
Fictional example
- Candidate
- Each step maps a number to a smaller one once it has a few digits, because each digit adds at most 81. So the values end up below about 243 and must repeat. The sequence either hits 1 or loops.
- Candidate
- The simple version keeps a set of seen values. To use constant memory I treat it like a linked list with a cycle and run a slow and a fast pointer.
- Candidate
- When they meet, I check whether the meeting point is 1. The first step costs log n for the digits, and the rest is bounded.
Related walkthroughs
Plus One is another digit-by-digit problem, this time carrying from the right. Pow(x, n) also turns a long repeated process into a short one by spotting structure. Single Number is the other math-flavored warm-up in this set, solved with XOR.
Where Natively fits
While you practice on a Mac or Windows PC, Natively can read a problem like this from a screenshot and suggest both the seen-set and the fast-and-slow approaches, and it can prompt you to explain why the process terminates. The transcript of your mock interview lets you check whether you mentioned the bound at all. The AI interview assistant page has details.
Questions people ask
How do you check if a number is happy?
Repeatedly replace it with the sum of the squares of its digits. If you reach 1 it is happy; if a value repeats, you are in a loop and it is not.
Why does the happy number process always stop?
Large numbers shrink quickly because each digit adds at most 81, so the values settle below a few hundred and must eventually repeat or reach 1.
How do you solve Happy Number without extra memory?
Use Floyd's cycle detection: a slow pointer takes one step and a fast pointer takes two. They meet inside the loop, and the number is happy if that loop is at 1.
What is the time complexity of Happy Number?
About O(log n): the first digit-square sum costs time proportional to the number of digits, and later values are small and bounded.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
