Smallest Number in Infinite Set

You have a set that starts out holding every positive integer `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: - `SmallestInfiniteSet()` creates the set containing all positive integers. - `int popSmallest()` removes and returns the smallest integer in the set. - `void addBack(int num)` adds `num` back into the set, if it is not already in it.

30:00

Smallest Number in Infinite Set
medium
Free written solution
Topics
Companies

You have a set that starts out holding every positive integer [1, 2, 3, 4, 5, ...].

Implement the SmallestInfiniteSet class:

  • SmallestInfiniteSet() creates the set containing all positive integers.
  • int popSmallest() removes and returns the smallest integer in the set.
  • void addBack(int num) adds num back into the set, if it is not already in it.
Example 1:
Input: {"commands":["SmallestInfiniteSet","addBack","popSmallest","popSmallest","popSmallest","addBack","popSmallest","popSmallest","popSmallest"],"values":[[],[2],[],[],[],[1],[],[],[]]}
Output: [null,null,1,2,3,null,1,4,5]
Constraints:
  • 1≤num≤10001 \leq \text{num} \leq 1000

  • At most 10001000 calls in total are made to popSmallest and addBack.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["SmallestInfiniteSet","addBack","popSmallest","popSmallest","popSmallest","addBack","popSmallest","popSmallest","popSmallest"],"values":[[],[2],[],[],[],[1],[],[],[]]}
new()
addBack(2)
popSmallest()
popSmallest()
popSmallest()
addBack(1)
popSmallest()
popSmallest()
popSmallest()

The set holds every positive integer. Store it as cur = 1 ("everything from cur up is present") plus a min-heap for numbers below cur that come back.

the set, as a number line

cur = 1

1

▲cur

2

▲cur

3

▲cur

4

▲cur

5

▲cur

6

▲cur

7

▲cur

8

▲cur

9

▲cur

10

▲cur

11

▲cur

12

▲cur

13

▲cur

14

▲cur

15

▲cur

16

▲cur

blue = never popped (cur and up, implicit) · green = added back (in heap) · struck = popped, absent

min-heap of added-back numbers (all < cur), smallest first

empty, so popSmallest takes cur

Returned values

[null]
Variables
VariableValue
cur1
DepthFunction Call
Stack empty
0/15