Skip to content
Decoder

Smallest Number in Infinite Set

Medium

Problem

Imagine a set that starts out holding every positive integer: 1, 2, 3, 4, and so on forever. Build a class SmallestInfiniteSet that supports:

- pop_smallest() (popSmallest in TypeScript): remove and return the smallest number currently in the set. - add_back(num) (addBack): put num back into the set if it is not already there.

Example 1

s = SmallestInfiniteSet()

Example 2

s.add_back(2)       # 2 is already in the set: nothing changes

Example 3

Input
s.pop_smallest()
Output
1

Example 4

Input
s.pop_smallest()
Output
2

Example 5

Input
s.pop_smallest()
Output
3

Example 6

s.add_back(1)       # 1 returns

Example 7

Input
s.pop_smallest()
Output
1

Example 8

Input
s.pop_smallest()
Output
4

Constraints

  • 1 <= num <= 1000
  • At most 1000 calls are made in total.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.