Browse curriculum

Smallest Number in Infinite Set (LeetCode 2336)

Smallest Number in Infinite Set (LeetCode 2336): design a set that starts with every positive integer, supports popSmallest and addBack. Keep a counter for the untouched tail of the set and a min-heap for numbers that were added back.

Problem Understanding

Smallest Number in Infinite Set (LeetCode 2336): design a class that starts with every positive integer [1, 2, 3, ...] and supports popSmallest(), which removes and returns the smallest number in the set, and addBack(num), which puts num back if it is not already there.

Example: addBack(2), then three pops return 1, 2, 3; addBack(1), then three pops return 1, 4, 5.

The Intuition: A Counter for the Tail, a Heap for the Returns

Pops always take from the front, so the set looks like this: a few numbers that came back, then an unbroken run from next to infinity.

  1. next is the smallest number never popped. Everything from it upward is in the set.
  2. A min-heap holds numbers below next that addBack returned, with a hash set to keep each in the heap once.
  3. popSmallest returns the heap’s top if there is one (it is always below next); otherwise it returns next and moves next on.
  4. addBack(num) pushes num only if num < next and it is not already in the heap.

The heap is the same tool as in Kth Largest Element in an Array; here it stores the small set of exceptions to a simple rule.

Smallest Number in Infinite Set Visualization

GREY = POPPED · TINTED = ADDED BACK, IN THE HEAP · next = START OF THE UNTOUCHED TAIL

next = 1, HEAP EMPTY

the set: 1, 2, 3, …

next

1
2
3
4
5
6
7

…

min-heap of added-back numbers

empty heap

next

1

heap size

0

operations

add 2
pop
pop
pop
add 1
pop
pop
pop

popSmallest returned

Nothing yet

 

Every number from next = 1 up is in the set; the heap of added-back numbers is empty

Next

addBack(2): 2 >= next = 1, so it was never removed. Nothing to do

Free preview: the first 3 of 9 steps

calls

The number line shows which numbers are in the set: greyed numbers were popped, tinted ones were added back and sit in the heap drawn underneath, and next marks the start of the untouched tail. Type your own calls, such as pop, pop, add 1, pop. Try Twice, where the same number is added back two times.

Smallest Number in Infinite Set Dry Run

Calls: addBack(2), pop, pop, pop, addBack(1), pop, pop, pop (LeetCode example 1).

Call Heap before next before What happens Returns
addBack(2) [] 1 2 >= next: already in the set
pop [] 1 heap empty: take next 1
pop [] 2 heap empty: take next 2
pop [] 3 heap empty: take next 3
addBack(1) [] 4 1 < next: push 1
pop [1] 4 pop the heap 1
pop [] 4 heap empty: take next 4
pop [] 5 heap empty: take next 5

Output: [null, null, 1, 2, 3, null, 1, 4, 5].

Smallest Number in Infinite Set LeetCode Solution

A counter, a min-heap and a membership set. JavaScript and TypeScript have no built-in heap, so they bring a small MinHeap; the C version uses a small array heap and a flag per number.

Smallest Number in Infinite Set Code
1class MinHeap {
2 constructor(less = (a, b) => a < b) {
3 this.items = [];
4 this.less = less;
5 }
6
7 size() {
8 return this.items.length;
9 }
10
11 peek() {
12 return this.items[0];
13 }
14
15 push(x) {
16 const a = this.items;
17 a.push(x);
18 let i = a.length - 1;
19 while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
20 const p = (i - 1) >> 1;
21 [a[i], a[p]] = [a[p], a[i]];
22 i = p;
23 }
24 }
25
26 pop() {
27 const a = this.items;
28 const top = a[0];
29 const last = a.pop();
30 if (a.length > 0) {
31 a[0] = last;
32 let i = 0;
33 while (true) {
34 const l = 2 * i + 1, r = l + 1;
35 let m = i;
36 if (l < a.length && this.less(a[l], a[m])) m = l;
37 if (r < a.length && this.less(a[r], a[m])) m = r;
38 if (m === i) break;
39 [a[i], a[m]] = [a[m], a[i]];
40 i = m;
41 }
42 }
43 return top;
44 }
45}
46
47var SmallestInfiniteSet = function() {
48 this.next = 1;
49 this.heap = new MinHeap();
50 this.added = new Set();
51};
52
53SmallestInfiniteSet.prototype.popSmallest = function() {
54 if (this.heap.size() > 0) {
55 const x = this.heap.pop();
56 this.added.delete(x);
57 return x;
58 }
59 return this.next++;
60};
61
62SmallestInfiniteSet.prototype.addBack = function(num) {
63 if (num < this.next && !this.added.has(num)) {
64 this.added.add(num);
65 this.heap.push(num);
66 }
67};

Smallest Number in Infinite Set in Python, Java, C++, TypeScript and C

Smallest Number in Infinite Set in Python
class SmallestInfiniteSet:
    def __init__(self):
        self.next = 1
        self.heap = []
        self.added = set()

    def popSmallest(self) -> int:
        if self.heap:
            x = heapq.heappop(self.heap)
            self.added.remove(x)
            return x
        self.next += 1
        return self.next - 1

    def addBack(self, num: int) -> None:
        if num < self.next and num not in self.added:
            self.added.add(num)
            heapq.heappush(self.heap, num)
Smallest Number in Infinite Set in Java
class SmallestInfiniteSet {
    private int next = 1;
    private final PriorityQueue<Integer> heap = new PriorityQueue<>();
    private final Set<Integer> added = new HashSet<>();

    public int popSmallest() {
        if (!heap.isEmpty()) {
            int x = heap.poll();
            added.remove(x);
            return x;
        }
        return next++;
    }

    public void addBack(int num) {
        if (num < next && added.add(num)) {
            heap.offer(num);
        }
    }
}
Smallest Number in Infinite Set in C++
class SmallestInfiniteSet {
    int next = 1;
    priority_queue<int, vector<int>, greater<int>> heap;
    unordered_set<int> added;

public:
    SmallestInfiniteSet() {}

    int popSmallest() {
        if (!heap.empty()) {
            int x = heap.top();
            heap.pop();
            added.erase(x);
            return x;
        }
        return next++;
    }

    void addBack(int num) {
        if (num < next && !added.count(num)) {
            added.insert(num);
            heap.push(num);
        }
    }
};
Smallest Number in Infinite Set in TypeScript
class MinHeap<T> {
    private items: T[] = [];

    constructor(private less: (a: T, b: T) => boolean = (a, b) => a < b) {}

    size(): number {
        return this.items.length;
    }

    peek(): T {
        return this.items[0];
    }

    push(x: T): void {
        const a = this.items;
        a.push(x);
        let i = a.length - 1;
        while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
            const p = (i - 1) >> 1;
            [a[i], a[p]] = [a[p], a[i]];
            i = p;
        }
    }

    pop(): T {
        const a = this.items;
        const top = a[0];
        const last = a.pop()!;
        if (a.length > 0) {
            a[0] = last;
            let i = 0;
            while (true) {
                const l = 2 * i + 1, r = l + 1;
                let m = i;
                if (l < a.length && this.less(a[l], a[m])) m = l;
                if (r < a.length && this.less(a[r], a[m])) m = r;
                if (m === i) break;
                [a[i], a[m]] = [a[m], a[i]];
                i = m;
            }
        }
        return top;
    }
}

class SmallestInfiniteSet {
    private next = 1;
    private heap = new MinHeap<number>();
    private added = new Set<number>();

    popSmallest(): number {
        if (this.heap.size() > 0) {
            const x = this.heap.pop();
            this.added.delete(x);
            return x;
        }
        return this.next++;
    }

    addBack(num: number): void {
        if (num < this.next && !this.added.has(num)) {
            this.added.add(num);
            this.heap.push(num);
        }
    }
}
Smallest Number in Infinite Set in C
/* Numbers are at most 1,000, so the heap is a small array and a flag per number. */
typedef struct {
    int next;
    int heap[1001];
    int size;
    bool added[1001];
} SmallestInfiniteSet;

SmallestInfiniteSet* smallestInfiniteSetCreate() {
    SmallestInfiniteSet* s = calloc(1, sizeof(SmallestInfiniteSet));
    s->next = 1;
    return s;
}

static void siftDown(int* h, int size, int i) {
    for (;;) {
        int m = i, l = 2 * i + 1, r = l + 1;
        if (l < size && h[l] < h[m]) m = l;
        if (r < size && h[r] < h[m]) m = r;
        if (m == i) return;
        int t = h[m]; h[m] = h[i]; h[i] = t;
        i = m;
    }
}

int smallestInfiniteSetPopSmallest(SmallestInfiniteSet* s) {
    if (s->size > 0) {
        int x = s->heap[0];
        s->heap[0] = s->heap[--s->size];
        siftDown(s->heap, s->size, 0);
        s->added[x] = false;
        return x;
    }
    return s->next++;
}

void smallestInfiniteSetAddBack(SmallestInfiniteSet* s, int num) {
    if (num < s->next && !s->added[num]) {
        s->added[num] = true;
        int i = s->size++;
        s->heap[i] = num;
        while (i > 0 && s->heap[(i - 1) / 2] > s->heap[i]) {
            int p = (i - 1) / 2, t = s->heap[p];
            s->heap[p] = s->heap[i];
            s->heap[i] = t;
            i = p;
        }
    }
}

void smallestInfiniteSetFree(SmallestInfiniteSet* s) {
    free(s);
}

Edge Cases & Common Mistakes

  • Adding back a number that was never popped: if num >= next it is still in the set; pushing it would return it twice.
  • Adding back the same number twice: without the membership set it enters the heap twice.
  • Forgetting to drop a popped number from the membership set: a later addBack of it would be ignored.
  • Comparing the heap top with next: unnecessary, because the heap only ever holds numbers below next.

Summary

A counter next stands for every number from it upward; a min-heap with a membership set holds the numbers below it that were added back. Pop from the heap when it has anything, otherwise from the counter. O(log n) per call, O(n) space for the heap.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start

    next = 1, an empty min-heap and an empty hash set.

  2. popSmallest

    If the heap is not empty, pop its top and drop it from the set; otherwise return next and add 1 to it.

  3. addBack(num)

    If num < next and num is not in the set, add it to the set and push it on the heap.

Frequently asked questions

How can a finite structure hold an infinite set?

Numbers are only ever removed from the front. So everything from some value `next` upward is still in the set, untouched, and one integer describes that whole tail. Only numbers below `next` need individual tracking, and only the ones that addBack returned.


Why is the heap’s top always smaller than next?

addBack only pushes a number that is below `next` (a number at or above it was never removed). `next` only grows, so everything in the heap stays below it. That is why popSmallest can take the heap’s top without comparing it with `next`.


Why keep a hash set beside the heap?

addBack(2) twice must not put 2 in the heap twice, or two later pops would both return 2. A heap cannot test membership quickly, so a hash set records which numbers are in it. A sorted set (TreeSet in Java, std::set in C++) can replace both.


What is the simpler approach with the constraints given?

Numbers stay at or below 1,000, so a boolean array of 1,001 entries and a scan from 1 for each pop also passes. It is O(1000) per pop. The counter and heap are the answer interviewers look for, because they do not depend on that bound.

New to the technique behind this problem? Watch it run step by step:

Heaps Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description