Skip to content
Problem 202 · LeetCode 202(opens in a new tab)

Happy Number

EasyHash tables

Take a positive whole number n, add up the squares of its digits, and replace n with that sum. Keep doing this. Some numbers reach 1 and then stay there, since 1² = 1. Others never reach 1 and go round the same loop of numbers forever.

A number that reaches 1 is called happy. Return true if n is happy and false otherwise.

Example 1

Input:  n = 7
Output: true
Why:    7 → 49 → 97 → 130 → 10 → 1
2 more examples and the constraints

Example 2

Input:  n = 4
Output: false
Why:    4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, a loop

Example 3

Input:  n = 1
Output: true
Why:    it is 1 already

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Remember every numberO(log n)
  2. Slow and fast pointersO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n near 2,147,483,647Verdict
Remember every numberO(log n)
Passes; easy to explain
Slow and fast pointersO(log n)
Best memory; a few more steps

n = the input number; log n is about its number of digits. Both are tiny in practice.

Edge cases to test

  • n = 1. Already happy. Check for 1 before deciding there is a loop.
  • Unhappy numbers. Every unhappy number ends up in the loop through 4, 16, 37, 58, 89, 145, 42, 20.
  • Largest input. 2,147,483,647 drops to 260 after one step, so big inputs are not slow.
  • Powers of ten. 10, 100 and 1,000,000,000 all go straight to 1.

Common mistakes

  • Looping until n is 1 with no loop check, which never ends on an unhappy number.
  • In Floyd's method, starting slow and fast on the same number, so the loop stops at once.
  • Squaring the whole number, or summing digits without squaring them.

How to talk through it

  1. 1Clarify. Is n always positive? Should I just return a boolean? Does it help to know the chain always ends or loops?
  2. 2Argue it cannot grow forever. A d-digit number maps to at most 81·d, so values fall below 1,000 fast. The chain must reach 1 or repeat.
  3. 3Use a set first. Store each number; a repeat means a loop. Simple and fast.
  4. 4Offer O(1) space. It is a linked list in disguise: move slow one step and fast two, and see whether they meet or fast hits 1.
  5. 5Test out loud. Run 1, 7 (happy) and 4 (the loop) before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?