2336. Smallest Number in Infinite Set
Medium
1.3K
126

You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`.

Implement the `SmallestInfiniteSet` class:

• `SmallestInfiniteSet()` Initializes the SmallestInfiniteSet object to contain all positive integers.
• `int popSmallest()` Removes and returns the smallest integer contained in the infinite set.
• `void addBack(int num)` Adds a positive integer `num` back into the infinite set, if it is not already in the infinite set.

Example 1:

```Input
[[], [2], [], [], [], [1], [], [], []]
Output
[null, null, 1, 2, 3, null, 1, 4, 5]

Explanation
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and
// is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.
```

Constraints:

• `1 <= num <= 1000`
• At most `1000` calls will be made in total to `popSmallest` and `addBack`.
Accepted
87.6K
Submissions
117K
Acceptance Rate
74.8%

Seen this question in a real interview before?
1/4
Yes
No

Discussion (0)

Related Topics