DSA Factory
Free Hashing lessonsHashing · Stage 3 · Sets for structure · Step 3

Have I been here before?

Follow a number sequence and use a set to notice when it loops. About 8 minutes.

Some processes go round in circles

Take a number, square each digit and add them up. 19 becomes 1 + 81 = 82, then 64 + 4 = 68, then 100, then 1. Some numbers reach 1 like that. Others circle forever through the same values: 4 goes round 16, 37, 58, 89, 145, 42, 20 and back to 4.

A plain loop can't tell "still going" from "stuck in a circle". You need a memory.

No memory: and a loop can run forever.
n = 19, replacing it by the sum of its digits' squares
1982681001
seen
{19}

Start at 19. Remember it in the seen set.

Move 1 of 5

A set of places you've been

Remember every number you've seen in a set, like leaving breadcrumbs in a maze. If you ever land on a number that's already in the set, you're walking in a circle that doesn't include 1, so stop and answer no.

If you reach 1, the answer is yes.

Seen it before? you're in a loop: the answer is no.
In code
seen = set()
while n != 1 and n not in seen:
    seen.add(n)
    n = sum(int(d) ** 2 for d in str(n))
return n == 1
Quick check

What comes after 82 in the digit-square process?

  1. A68
  2. B10
  3. C1
Show the answer

68. 8² + 2² = 64 + 4 = 68.

Your problem

Happy number

Starting from n, repeatedly replace the number by the sum of the squares of its digits. Return true if this reaches 1, and false if it loops forever without reaching 1.

Example
n = 19 → true

1 ≤ n ≤ 2,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve