15% off all plans & roadmaps Use code
See plansHappy Number
- LeetCode 202
- Easy
- Two Pointers
- Fast & Slow (Cycle Detection)
Updated
TL;DR: Replace a number by the sum of the squares of its digits until it hits 1 or repeats. Detect the repeat with a hash set, or with slow and fast pointers in O(1) space.
Problem
Write an algorithm that decides whether a number n is happy.
A happy number is defined by this process:
- Start with any positive integer and replace it with the sum of the squares of its digits.
- Repeat the step until the number equals 1 (where it stays), or until it loops endlessly in a cycle that does not contain 1.
- A number is happy if the process ends at 1.
Return true if n is happy, and false otherwise.
Example 1
Input: n = 19 Output: true Explanation: 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1
Example 2
Input: n = 2 Output: false
Constraints
1 <= n <= 2^31 - 1
Constraints that matter
ngoes up to 2^31 - 1, which has at most 10 digits. One digit-sum step costs at most 10 operations, so a single step is cheap.- The largest possible digit-square sum of a 10-digit number is 10 * 81 = 810. After one step the value is at most 810, and after two steps it is at most 243. The sequence cannot grow without bound.
- Every value lives in a small bounded range, so the sequence must reach 1 or repeat within a few hundred steps. A plain
while n != 1loop is therefore unsafe, but a repeat check always terminates. - There are no negative numbers or zero. You never have to handle
n = 0, which would stay at 0 forever and never reach 1. - The sum of squares never overflows a 32-bit integer, so you do not need a
longin Java, C++ or C#.
Hints
Hint 1
Treat the process as a walk on a graph where every number has exactly one outgoing edge, to the sum of the squares of its digits.
Hint 2
Follow the process exactly as written.
Solution
Intuition
Treat the process as a walk on a graph where every number has exactly one outgoing edge, to the sum of the squares of its digits. A walk that follows single edges can only do two things. It reaches a node that points to itself, which is 1 here, or it falls into a loop. This is the Fast & Slow Pointers (cycle detection) pattern, the same one that finds a cycle in a linked list.
It is like two runners on a circular track, one jogging and one sprinting twice as fast. The slow runner is the slow pointer, the fast runner is the fast pointer, and meeting again means the walk has looped.
Can the walk run forever without repeating? It cannot. A 10-digit number maps to at most 810, and anything below 1000 maps to at most 243. After two steps you are inside the range 1 to 243, so within about 245 steps some value must repeat or you must hit 1.
The unhappy numbers all end in the same loop: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. Starting from 2 you walk 2 → 4 and then circle that loop forever. You do not need that fact to solve the problem. You only need a reliable way to notice that you have seen a value before.
There are two ways to notice. You can remember every value you have visited and check each new one against that memory. Or you can run two walkers at different speeds and wait for them to meet. The second costs two variables instead of a collection.
Worked example
Input: n = 1000000000 Output: true Explanation: The digits of 1000000000 are a 1 followed by nine zeros. The sum of squares is 1^2 + 0 + ... + 0 = 1, so the very first step lands on 1 and the number is happy.
Approach 1: Brute force: list of visited numbers
Follow the process exactly as written. After each step, ask whether the new number is 1. If it is not, ask whether you have been at this number before. If you have, you are in a loop that skips 1, so return false.
The beginner version stores the visited numbers in a plain list and scans the whole list for every new number. That scan is the repeated work the next approach removes.
Steps
- Write a helper
next(x)that returns the sum of the squares of the digits ofx. - Create an empty list
seen. - While
nis not 1, scanseenforn. If it is there, returnfalse. - Otherwise append
ntoseenand setn = next(n). - When the loop exits,
nis 1, so returntrue.
Dry run
Trace n = 1000000000.
nis 1000000000, not 1.seenis empty, so no repeat. Append it, soseen = [1000000000].- Compute
next(1000000000). The only non-zero digit is the leading 1, so the result is 1. Nown = 1. - The loop condition
n != 1is false, so the loop ends. - Return
true, which matches the expected output.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the input value. The first digit-sum costs O(log n) because n has about log10(n) digits. After that every value is at most 810, so each later step costs a constant number of operations. The list holds at most about 245 distinct values before a repeat or a 1 appears. The scans therefore cost at most roughly 245 * 245 operations, a constant that does not depend on n. Space is bounded by that same constant list size.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isHappy(self, n: int) -> bool:
def next_num(x: int) -> int:
total = 0
while x > 0:
x, d = divmod(x, 10)
total += d * d
return total
seen = []
while n != 1:
if n in seen: # linear scan of the history
return False
seen.append(n)
n = next_num(n)
return True
JavaTested in our runner
import java.util.*;
class Solution {
private int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public boolean isHappy(int n) {
List<Integer> seen = new ArrayList<>();
while (n != 1) {
if (seen.contains(n)) {
return false;
}
seen.add(n);
n = next(n);
}
return true;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
class Solution {
int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public:
bool isHappy(int n) {
std::vector<int> seen;
while (n != 1) {
if (std::find(seen.begin(), seen.end(), n) != seen.end()) {
return false;
}
seen.push_back(n);
n = next(n);
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
const next = (x) => {
let total = 0;
while (x > 0) {
const d = x % 10;
total += d * d;
x = Math.floor(x / 10);
}
return total;
};
const seen = [];
while (n !== 1) {
if (seen.includes(n)) {
return false;
}
seen.push(n);
n = next(n);
}
return true;
};
GoTested in our runner
func nextNum(x int) int {
total := 0
for x > 0 {
d := x % 10
total += d * d
x /= 10
}
return total
}
func isHappy(n int) bool {
seen := []int{}
for n != 1 {
for _, v := range seen {
if v == n {
return false
}
}
seen = append(seen, n)
n = nextNum(n)
}
return true
}
C#Tested in our runner
public class Solution {
private static int Next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public bool isHappy(int n) {
var seen = new List<int>();
while (n != 1) {
if (seen.Contains(n)) {
return false;
}
seen.Add(n);
n = Next(n);
}
return true;
}
}
Approach 2: Hash set of visited numbers
What's slow in the list version is the membership test. Every new number is compared against every stored number, so each check costs time proportional to the history length.
The insight that fixes it is that a hash set answers 'have I seen this value' in constant expected time. The algorithm is otherwise identical. You still walk the sequence one step at a time and stop at 1 or at a repeat.
Steps
- Write the helper
next(x)that sums the squares of the digits. - Create an empty hash set
seen. - While
nis not 1, check whethernis already inseen. If it is, returnfalse. - Insert
nintoseen, then replacenwithnext(n). - When the loop ends, return
true.
Dry run
Trace n = 1000000000.
| Step | n | in seen? | seen after step |
|---|---|---|---|
| start | 1000000000 | no | {} |
| 1 | 1000000000 | no, so insert | {1000000000} |
| 2 | next gives 1 | loop ends | {1000000000} |
The loop condition fails at n = 1, so the function returns true, which matches the expected output. For an unhappy input such as 2, the set would grow as {2}, {2, 4}, {2, 4, 16}, and so on until 4 appears a second time.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the input value. The first step costs O(log n) for the digits of n, and every later value is at most 810, so each later step is constant work. Before a repeat or a 1, the walk visits at most about 245 distinct values. Each hash lookup and insert is constant expected time, so the loop is bounded by a constant. The set never holds more than that many integers, so space is bounded by a constant. It is still a real collection that the next approach avoids.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isHappy(self, n: int) -> bool:
def next_num(x: int) -> int:
total = 0
while x > 0:
x, d = divmod(x, 10)
total += d * d
return total
seen = set()
while n != 1:
if n in seen: # repeat means a cycle that skips 1
return False
seen.add(n)
n = next_num(n)
return True
JavaTested in our runner
import java.util.*;
class Solution {
private int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1) {
if (!seen.add(n)) {
return false;
}
n = next(n);
}
return true;
}
}
C++Tested in our runner
#include <unordered_set>
class Solution {
int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public:
bool isHappy(int n) {
std::unordered_set<int> seen;
while (n != 1) {
if (!seen.insert(n).second) {
return false;
}
n = next(n);
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
const next = (x) => {
let total = 0;
while (x > 0) {
const d = x % 10;
total += d * d;
x = Math.floor(x / 10);
}
return total;
};
const seen = new Set();
while (n !== 1) {
if (seen.has(n)) {
return false;
}
seen.add(n);
n = next(n);
}
return true;
};
GoTested in our runner
func nextNum(x int) int {
total := 0
for x > 0 {
d := x % 10
total += d * d
x /= 10
}
return total
}
func isHappy(n int) bool {
seen := map[int]bool{}
for n != 1 {
if seen[n] {
return false
}
seen[n] = true
n = nextNum(n)
}
return true
}
C#Tested in our runner
public class Solution {
private static int Next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public bool isHappy(int n) {
var seen = new HashSet<int>();
while (n != 1) {
if (!seen.Add(n)) {
return false;
}
n = Next(n);
}
return true;
}
}

Solution pattern
Fast & Slow (Cycle Detection)
Part of Two Pointers
Approach 3: Fast and slow pointersOptimalFast & Slow (Cycle Detection)
What's slow, or rather heavy, in the hash set version is the memory. It stores every visited value only to answer one question: did the walk loop back? Interviewers often ask for a version that stores nothing.
The insight that fixes it is Floyd's cycle detection. Run a slow walker that moves one step per round and a fast walker that moves two steps per round. If the sequence ends at 1, the fast walker reaches 1 first. If the sequence enters a loop, both walkers end up inside it, and the fast one gains one position per round on the slow one, so they must land on the same value.
Because 1 maps to itself, a happy number also makes the walkers meet, at 1. The code therefore stops as soon as the fast walker is 1 or the two are equal, then checks which case happened.
Steps
- Write the helper
next(x)that sums the squares of the digits. - Set
slow = nandfast = next(n), so the walkers start one step apart and the equality test is not true on entry. - Loop while
fast != 1andslow != fast. - Inside the loop, move
slowone step withnext(slow). - Move
fasttwo steps withnext(next(fast)). - After the loop, return
fast == 1.
Dry run
Trace the example n = 1000000000.
| Step | slow | fast | fast == 1? | slow == fast? | Action |
|---|---|---|---|---|---|
| init | 1000000000 | next(1000000000) = 1 | yes | no | check loop condition |
| loop test | 1000000000 | 1 | yes | no | condition fast != 1 is false, exit |
| return | 1000000000 | 1 | yes | no | return fast == 1, which is true |
The example is happy after one step, so the loop body never runs. To see the pointers move, trace n = 19. Start with slow = 19, fast = 82.
Round 1 gives slow = 82 and fast = next(next(82)) = next(68) = 100. Round 2 gives slow = 68 and fast = next(next(100)) = next(1) = 1. Now fast == 1, so the function returns true.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the input value. The first digit-sum costs O(log n), and every later value is at most 810, so each step afterward is constant work. Once the walkers are inside the bounded range, the tail before the loop plus the loop length is at most about 245 values. The gap between the walkers closes by one per round, so the number of rounds is bounded by a constant. Space is two integer variables, independent of n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isHappy(self, n: int) -> bool:
def next_num(x: int) -> int:
total = 0
while x > 0:
x, d = divmod(x, 10)
total += d * d
return total
slow = n
fast = next_num(n) # start one step ahead so slow != fast on entry
while fast != 1 and slow != fast:
slow = next_num(slow)
fast = next_num(next_num(fast))
return fast == 1
JavaTested in our runner
class Solution {
private int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public boolean isHappy(int n) {
int slow = n;
int fast = next(n);
while (fast != 1 && slow != fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast == 1;
}
}
C++Tested in our runner
class Solution {
int next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public:
bool isHappy(int n) {
int slow = n;
int fast = next(n);
while (fast != 1 && slow != fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast == 1;
}
};
JavaScriptTested in our runner
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
const next = (x) => {
let total = 0;
while (x > 0) {
const d = x % 10;
total += d * d;
x = Math.floor(x / 10);
}
return total;
};
let slow = n;
let fast = next(n);
while (fast !== 1 && slow !== fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast === 1;
};
GoTested in our runner
func nextNum(x int) int {
total := 0
for x > 0 {
d := x % 10
total += d * d
x /= 10
}
return total
}
func isHappy(n int) bool {
slow := n
fast := nextNum(n)
for fast != 1 && slow != fast {
slow = nextNum(slow)
fast = nextNum(nextNum(fast))
}
return fast == 1
}
C#Tested in our runner
public class Solution {
private static int Next(int x) {
int total = 0;
while (x > 0) {
int d = x % 10;
total += d * d;
x /= 10;
}
return total;
}
public bool isHappy(int n) {
int slow = n;
int fast = Next(n);
while (fast != 1 && slow != fast) {
slow = Next(slow);
fast = Next(Next(fast));
}
return fast == 1;
}
}
Common mistakes
- Writing
while n != 1: n = next(n)with no repeat check. An unhappy number such as 2 cycles through 4, 16, 37, 58, 89, 145, 42, 20 forever, so the loop never ends. Add a visited set or the slow and fast pointers. - Inserting into the set before the lookup, as in
seen.add(n)followed byif n in seen. The check then always succeeds and you returnfalsefor every input. Test membership first, then insert, or use the return value ofadd. - Starting both pointers at
nand looping onwhile slow != fast. The condition is false on entry, so the loop never runs. Startfastatnext(n), or use a do-while loop. - Destroying the input while summing digits and then reusing it. If you shrink
nwithn //= 10inside the helper on the same variable you store, you lose the value you meant to record. Copy it into a local variable insidenext. - Looping
while x > 1in the digit helper. A digit sum for x = 1 is skipped and the helper returns 0 for single-digit inputs like 1, which is wrong. Loop whilex > 0so every digit, including the last, is squared. - Moving the fast pointer only once per round, as in
fast = next(fast). Both pointers then travel at the same speed and the gap never closes inside a cycle. Applynexttwice tofasteach round. - Checking only
slow == 1at the end. The fast pointer reaches 1 first, and the slow pointer may still be at 100 when the loop exits. Returnfast == 1.
Edge cases
n = 1: already 1, so the answer istrue. The Floyd code setsfast = next(1) = 1and exits immediately.n = 7: happy, 7 → 49 → 97 → 130 → 10 → 1. Returnstrue.n = 2: unhappy, it enters the loop through 4. Returnsfalse.n = 4: sits inside the unhappy loop, so it is unhappy. Returnsfalse.n = 2147483647(the maximum): the first step gives 4+1+16+64+16+81+16+64+36+49 = 347, which stays small. No overflow, and the answer comes from normal iteration.n = 1000000000: a power of ten, whose digit-square sum is 1. Returnstrueafter one step.n = 10,100,1000: every power of ten collapses to 1 on the first step. All returntrue.
Follow-ups interviewers ask
- Can you solve it with O(1) extra space?
- Yes. Use slow and fast pointers. Slow applies the digit-square step once per round and fast applies it twice. The loop stops when fast reaches 1 or the two are equal. That stores two integers and no collection.
- Can you skip cycle detection by using what you know about the unhappy loop?
- Yes. Every unhappy number falls into the loop that contains 4. So loop
while n != 1 and n != 4: n = next(n)and returnn == 1. This uses O(1) space with no pointers. You must justify the fact about the loop, though. General cycle detection does not depend on that fact, which is why the pointer version is safer to explain. - How would you count happy numbers up to a large limit, say 10^7?
- Memoize the answer for every value in 1 to 810, since every digit-square sum of a number up to 10^7 is at most 7 * 81 = 567. Then for each number, apply one digit-square step and look up the stored answer. Each number costs one digit pass instead of a full walk. You can also fill the table with the same cycle detection run once per small value.
Happy Number FAQ
What is the time complexity of Happy Number?
It is O(log n) for the input value n. The first digit-sum reads about log10(n) digits, and every later value is at most 810, so the rest of the walk costs a bounded constant. The sequence always reaches 1 or repeats within about 245 steps.
Why use fast and slow pointers for Happy Number?
Each number has exactly one next number, so the sequence behaves like a linked list that either ends at 1 or loops. Slow and fast pointers detect that loop without storing the visited numbers. If the sequence loops, the fast pointer gains one position per round on the slow pointer, so they must meet.
Can Happy Number be solved in O(1) extra space?
Yes. Floyd's slow and fast pointers keep two integers and no set. The hash set version is also bounded by a constant, since at most about 245 values appear. It still allocates a collection that the pointer version does not.
What is the logic of happy numbers?
Replace the number with the sum of the squares of its digits, and repeat. If you reach 1, the number is happy because 1 maps to itself. If you repeat any other value, you are in a loop and the number is not happy. For example, 19 goes 82, 68, 100, 1, so it is happy.
What is a non-cyclical number in this problem?
A happy number has a non-cyclical path in the sense that it ends at the fixed point 1 instead of looping through other values. An unhappy number is cyclical. It enters the loop 4, 16, 37, 58, 89, 145, 42, 20 and repeats.
Can the sequence grow forever instead of looping?
No. A number with d digits maps to at most 81 * d. For d up to 10 that is at most 810, and for any number below 1000 the result is at most 243. The values stay bounded, so by the pigeonhole principle some value repeats unless 1 is reached first.
Asked at
See which companies ask this — Pro
Related problems
- Contains Duplicate · same technique: Fast & Slow (Cycle Detection)
- Linked List Cycle · same technique: Fast & Slow (Cycle Detection)
- Contains Duplicate II · same technique: Fast & Slow (Cycle Detection)
- Sort Colors · next harder, same pattern
- Two Sum · same pattern: Two Pointers
- Valid Anagram · same pattern: Two Pointers
- Plus One · same pattern: Two Pointers
- Missing Number · same pattern: Two Pointers
- Remove Duplicates from Sorted Array · same pattern: Two Pointers
- Remove Element · same pattern: Two Pointers