#2336

Smallest Number in Infinite Set

Medium
Hash TableDesignHeap (Priority Queue)Ordered SetHeapPriority Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(n)
O(n)
💡

Intuition

Time O(log n)Space O(n)

The optimal approach uses a priority queue (min-heap) to efficiently manage the smallest available numbers and a set to track which numbers have been added back. This allows us to quickly pop the smallest number and manage additions without scanning through a list.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a min-heap to store numbers that have been added back.
  2. 2Step 2: Maintain a variable for the current smallest number to be popped.
  3. 3Step 3: For popSmallest(), check the heap for the smallest number, or return the current smallest if the heap is empty, then increment the current smallest.
  4. 4Step 4: For addBack(num), add num to the heap if it's less than the current smallest.
solution.py16 lines
1import heapq
2class SmallestInfiniteSet:
3    def __init__(self):
4        self.min_heap = []
5        self.current = 1
6
7    def popSmallest(self):
8        if self.min_heap:
9            return heapq.heappop(self.min_heap)
10        smallest = self.current
11        self.current += 1
12        return smallest
13
14    def addBack(self, num):
15        if num < self.current:
16            heapq.heappush(self.min_heap, num)

Complexity note: The time complexity is O(log n) for each popSmallest and addBack operation due to the heap operations, making it efficient compared to the brute force approach.

  • 1Using a heap allows efficient retrieval of the smallest number.
  • 2Tracking the current smallest number helps manage additions effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.