Smallest Number in Infinite Set Problem
#2336
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2336.
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 integernumback into the infinite set, if it is not already in the infinite set.
Example 1:
Input
["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
[[], [2], [], [], [], [1], [], [], []]
Output
[null, null, 1, 2, 3, null, 1, 4, 5]
Explanation
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.
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.addBack(1); // 1 is added back to 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
1000calls will be made in total topopSmallestandaddBack.
Solution
Approach: Ordered Set
Only the numbers that were popped and might be added back matter, and there are at most 1000 calls in total, so no pop ever goes beyond 1000. We can therefore store the numbers 1..1000 in an ordered set (a balanced tree or sorted set).
popSmallestremoves and returns the smallest element of the set.addBack(num)insertsnum; the set ignores it when it is already present.
Complexity: Time O(log n) per call and O(n log n) for the constructor, space O(n), where n = 1000 is the largest possible number.
import heapq
class SmallestInfiniteSet:
def __init__(self):
self.s = set(range(1, 1001))
self.h = list(range(1, 1001))
def popSmallest(self) -> int:
x = heapq.heappop(self.h)
self.s.remove(x)
return x
def addBack(self, num: int) -> None:
if num not in self.s:
self.s.add(num)
heapq.heappush(self.h, num)
# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)