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)
s = SmallestInfiniteSet()
s.addBack(2)
assert [s.popSmallest(), s.popSmallest(), s.popSmallest()] == [1, 2, 3]
s.addBack(1)
assert [s.popSmallest(), s.popSmallest(), s.popSmallest()] == [1, 4, 5]
s2 = SmallestInfiniteSet()
s2.popSmallest(); s2.popSmallest()
s2.addBack(1); s2.addBack(1)
assert [s2.popSmallest(), s2.popSmallest()] == [1, 3]
class SmallestInfiniteSet {
private int nxt = 1;
private final TreeSet<Integer> back = new TreeSet<>(); // re-added numbers below nxt
public int popSmallest() { return back.isEmpty() ? nxt++ : back.pollFirst(); }
public void addBack(int num) { if (num < nxt) back.add(num); }
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
type SmallestInfiniteSet struct {
next int // every number >= next is in the set
back IntHeap // numbers < next that were added back
inBack map[int]bool // ...and their membership
}
func Constructor() SmallestInfiniteSet {
return SmallestInfiniteSet{next: 1, inBack: map[int]bool{}}
}
func (this *SmallestInfiniteSet) PopSmallest() int {
if this.back.Len() > 0 {
x := heap.Pop(&this.back).(int)
delete(this.inBack, x)
return x
}
this.next++
return this.next - 1
}
func (this *SmallestInfiniteSet) AddBack(num int) {
if num < this.next && !this.inBack[num] {
this.inBack[num] = true
heap.Push(&this.back, num)
}
}