Skip to content

Smallest Number in Infinite Set

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

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.
s = SmallestInfiniteSet()
s.add_back(2)       # 2 is already in the set: nothing changes
s.pop_smallest()    →  1
s.pop_smallest()    →  2
s.pop_smallest()    →  3
s.add_back(1)       # 1 returns
s.pop_smallest()    →  1
s.pop_smallest()    →  4

Constraints

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