15% off all plans & roadmaps Use code

See plans

Happy Number

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

  • n goes 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 != 1 loop 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 long in Java, C++ or C#.

View on LeetCode

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.

Watch the pattern animation

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

  1. Write a helper next(x) that returns the sum of the squares of the digits of x.
  2. Create an empty list seen.
  3. While n is not 1, scan seen for n. If it is there, return false.
  4. Otherwise append n to seen and set n = next(n).
  5. When the loop exits, n is 1, so return true.

Dry run

Trace n = 1000000000.

  1. n is 1000000000, not 1. seen is empty, so no repeat. Append it, so seen = [1000000000].
  2. Compute next(1000000000). The only non-zero digit is the leading 1, so the result is 1. Now n = 1.
  3. The loop condition n != 1 is false, so the loop ends.
  4. Return true, which matches the expected output.

Complexity

TimeO(log n)
SpaceO(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

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

  1. Write the helper next(x) that sums the squares of the digits.
  2. Create an empty hash set seen.
  3. While n is not 1, check whether n is already in seen. If it is, return false.
  4. Insert n into seen, then replace n with next(n).
  5. When the loop ends, return true.

Dry run

Trace n = 1000000000.

Stepnin seen?seen after step
start1000000000no{}
11000000000no, so insert{1000000000}
2next gives 1loop 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

TimeO(log n)
SpaceO(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
Fast & Slow (Cycle Detection) pattern infographic for Happy Number

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

  1. Write the helper next(x) that sums the squares of the digits.
  2. Set slow = n and fast = next(n), so the walkers start one step apart and the equality test is not true on entry.
  3. Loop while fast != 1 and slow != fast.
  4. Inside the loop, move slow one step with next(slow).
  5. Move fast two steps with next(next(fast)).
  6. After the loop, return fast == 1.

Dry run

Trace the example n = 1000000000.

Stepslowfastfast == 1?slow == fast?Action
init1000000000next(1000000000) = 1yesnocheck loop condition
loop test10000000001yesnocondition fast != 1 is false, exit
return10000000001yesnoreturn 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

TimeO(log n)
SpaceO(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

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 by if n in seen. The check then always succeeds and you return false for every input. Test membership first, then insert, or use the return value of add.
  • Starting both pointers at n and looping on while slow != fast. The condition is false on entry, so the loop never runs. Start fast at next(n), or use a do-while loop.
  • Destroying the input while summing digits and then reusing it. If you shrink n with n //= 10 inside the helper on the same variable you store, you lose the value you meant to record. Copy it into a local variable inside next.
  • Looping while x > 1 in 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 while x > 0 so 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. Apply next twice to fast each round.
  • Checking only slow == 1 at the end. The fast pointer reaches 1 first, and the slow pointer may still be at 100 when the loop exits. Return fast == 1.

Edge cases

  • n = 1: already 1, so the answer is true. The Floyd code sets fast = next(1) = 1 and exits immediately.
  • n = 7: happy, 7 → 49 → 97 → 130 → 10 → 1. Returns true.
  • n = 2: unhappy, it enters the loop through 4. Returns false.
  • n = 4: sits inside the unhappy loop, so it is unhappy. Returns false.
  • 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. Returns true after one step.
  • n = 10, 100, 1000: every power of ten collapses to 1 on the first step. All return true.

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 return n == 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

Practise it