InterviewPrepKit

Home / Coding / Math & Geometry

Happy Number

easy Original β†—
Solving tips
  • The process either reaches 1 or falls into a cycle, so this is really cycle detection on the sequence x -> sum of squares of digits.
  • Simplest: keep a set of seen values; exit True when you hit 1, False when you revisit a value.
  • For O(1) space, apply Floyd's tortoise-and-hare (slow one step, fast two steps) treating next_num as the 'next' pointer; start fast one step ahead.
  • Compute sum of SQUARES of digits (a common slip is summing the digits); values quickly bound below 243, so runtime is effectively O(log n).

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 = 19 β†’ True β€” 19 β†’ 1Β²+9Β²=82 β†’ 8Β²+2Β²=68 β†’ 6Β²+8Β²=100 β†’ 1Β²+0Β²+0Β²=1.
  • n = 2 β†’ False β€” the sequence 2 β†’ 4 β†’ 16 β†’ 37 β†’ 58 β†’ 89 β†’ 145 β†’ 42 β†’ 20 β†’ 4 β†’ ... cycles back to 4 without ever hitting 1.
  • n = 7 β†’ True β€” 7 β†’ 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 β€” a cycle. So detecting a repeat is the whole game.
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 β€” exactly what Floyd's tortoise-and-hare does with O(1) extra memory. Run a slow pointer one step and a fast pointer two steps; if they meet at 1, happy; if they meet elsewhere, it's a loop.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.