Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Does the digit-square sequence reach 1

Easy · Target 10 minutes · Two pointers· Type asked at

You start with a positive integer n and keep replacing it with the sum of the squares of its digits, and if you eventually get to 1 then n is called happy. You'd return true if it is and false if the sequence ends up going round a loop that never has 1 in it.

Examples

InputOutputWhy
n = 19true19 → 82 → 68 → 100 → 1.
n = 2false2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and you're back at 4 for good.
n = 7true7 → 49 → 97 → 130 → 10 → 1.

Constraints

  • 1 ≤ n ≤ 2³¹ − 1

Hints

Hint 1

Do you think the sequence could just keep on growing? I'd look at what happens to a number with ten digits and ask how big the sum of the squares of its digits could possibly be.

Hint 2

It's at most 10 × 81 = 810, so after one step you're below 1,000 and you'll stay there. That means the sequence has to repeat, and either it gets to 1 (which maps to itself) or it goes round a loop.

Hint 3

You could keep every value you've seen in a set, or you can run a slow pointer one step at a time and a fast one two steps at a time and stop when they meet, and then check whether it was at 1 that they met.

Where people lose marks

  • Looping until you see 1 with nothing else to stop you, which never ends on a number like 2.
  • Checking only for 4 as the sign of an unhappy number. It happens to be true that every unhappy number reaches 4, but it's a fact you'd have to prove in the interview, and cycle detection doesn't need it.
  • Overflow when n is close to 2³¹. The sum of the squares of ten digits is at most 810, so the step itself is safe, as long as you don't square the whole number by mistake.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.