InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Happy Number

easy Original ↗ 00:00

Problem

Define one step on a positive integer as: replace the number by the sum of the squares of its digits. A number is happy if repeatedly applying this step eventually reaches 1. If the process instead falls into a loop that never contains 1, the number is not happy. Given n, return True if it is happy, otherwise False.

Examples

  • n = 19True19 → 1²+9²=82 → 8²+2²=68 → 6²+8²=100 → 1²+0²+0²=1.
  • n = 2False — the sequence 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ... cycles back to 4 without ever hitting 1.
  • n = 7True7 → 49 → 97 → 130 → 10 → 1.

Constraints

  • 1 <= n <= 2^31 - 1

Think about it first

Hint 1 The process either reaches 1 or runs forever. Running forever means it must eventually revisit a number it has already seen, which is a cycle. Detecting a repeated value is enough to decide the answer.
Hint 2 Store every number you have already produced in a set. If you ever generate a number already in the set (and it isn't 1), you're in a cycle and the answer is `False`.
Hint 3 This is a "does the sequence terminate or cycle" question, which Floyd's tortoise-and-hare solves with O(1) extra memory. Run a slow pointer one step and a fast pointer two steps; if they meet at 1, the number is happy; if they meet elsewhere, the sequence loops.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug