Smallest Number in Infinite Set (LeetCode 2336): Solution and Explanation

Medium
Hash Table
Design
Heap Priority Queue
Ordered Set

A set starts with every positive integer. Support popSmallest, which removes and returns the smallest member, and addBack(num), which puts num back if it is missing.

Intuition

An infinite set cannot be stored directly, but most of it never changes. After k pops with no addBack calls, the set is exactly every integer from k + 1 upward. That tail is fully described by one number, cur.

Numbers below cur were popped at some point. The only way one of them is present again is through addBack, so those few numbers can be kept explicitly. They are all smaller than cur, which means that whenever any of them exist, the smallest of them is the answer to popSmallest.

A min-heap gives that smallest added-back number quickly. A hash set next to it answers "is this number already back?" in O(1), which stops a duplicate push that would later be popped twice. An addBack with num >= cur is a no-op because the number was never removed.

Approach: Pointer plus min-heap

  1. Start with cur = 1, an empty min-heap and an empty hash set.
  2. popSmallest: if the heap is non-empty, pop its minimum, remove it from the hash set and return it.
  3. Otherwise return cur and increment cur.
  4. addBack(num): if num < cur and num is not in the hash set, add it to the set and push it onto the heap. Otherwise do nothing.

Step-by-step example

addBack(2), pop, pop, pop, addBack(1), pop, pop, pop
  1. addBack(2): 2 >= cur = 1, so 2 was never removed. Nothing changes.
  2. Three pops with an empty heap return 1, 2, 3 and move cur to 4.
  3. addBack(1): 1 < 4 and not in the heap, so push it. Heap = [1].
  4. pop: the heap has 1, which is below cur, so return 1. Heap is empty again.
  5. Two more pops return 4 and 5. Output: [null, null, 1, 2, 3, null, 1, 4, 5].

Code: Python, Java, C++

1import heapq
2
3class SmallestInfiniteSet:
4    def __init__(self):
5        self.cur = 1
6        self.heap = []
7        self.added = set()
8
9    def popSmallest(self) -> int:
10        if self.heap:
11            num = heapq.heappop(self.heap)
12            self.added.remove(num)
13            return num
14        self.cur += 1
15        return self.cur - 1
16
17    def addBack(self, num: int) -> None:
18        if num < self.cur and num not in self.added:
19            self.added.add(num)
20            heapq.heappush(self.heap, num)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log k) per call

Heap push and pop cost O(log k), where k is the number of added-back values; the pointer path and the hash set checks are O(1).

Space

O(k)

Only the added-back numbers below cur are stored, at most min(cur, number of addBack calls).

Other approaches

Ordered set below cur (time O(log k) per call, space O(k))

Replace the heap and hash set with one ordered set (TreeSet, SortedSet, std::set). It removes duplicates by itself and gives the minimum directly. Same complexity, less bookkeeping.

Boolean array over the bounded range (time O(range) per pop, space O(range))

Since num <= 1000 and there are at most 1000 calls, every relevant number is at most about 2000. Keep a presence array and scan from the left for the first true value. Simple, but O(range) per pop and tied to the constraints.

Common mistakes

  • Pushing a number that is already back into the heap. Without the hash set check it gets popped twice.
  • Accepting addBack(num) for num >= cur. That number was never removed, so adding it to the heap would return it twice.
  • Checking cur before the heap in popSmallest. Every heap entry is smaller than cur, so the heap must be checked first.

Frequently asked questions

Why is every number in the heap smaller than cur?

addBack only pushes numbers below cur, and cur never decreases. So once a number enters the heap it stays below cur.

Why do the JavaScript and Go versions use a sorted array?

Neither language has a built-in priority queue. With at most 1000 calls, a sorted array with binary or linear insertion is fast enough, and it behaves exactly like the heap plus set: the first element is the minimum and duplicates are rejected.

Does the set ever need to remember numbers above cur?

No. Everything from cur upward is present by definition, which is what makes the infinite set fit in a single integer.