SDE & MLE Prep

2336. Smallest Number in Infinite Set

Problem

Design SmallestInfiniteSet, which starts out containing every positive integer: popSmallest() removes and returns the smallest number in it, and addBack(num) puts num back if it is missing.

Example: addBack(2), then popSmallest() ×3 → 1, 2, 3; addBack(1) → popSmallest() = 1, then 4

Constraints: up to 1000 calls; num ≤ 1000.

Every integer ≥ nxt is still present — no need to store them. Numbers added back below nxt go into a min-heap (with a set to avoid duplicates). Pop from the heap if it's non-empty, otherwise hand out nxt and increment it.

Complexity: O(log n) per operation.

class SmallestInfiniteSet:
    def __init__(self):
        self.nxt = 1
        self.back, self.in_back = [], set()

    def popSmallest(self) -> int:
        if self.back:
            x = heappop(self.back)
            self.in_back.remove(x)
            return x
        self.nxt += 1
        return self.nxt - 1

    def addBack(self, num: int) -> None:
        if num < self.nxt and num not in self.in_back:
            self.in_back.add(num)
            heappush(self.back, num)