Smallest Number in Infinite Set - Problem

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.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["SmallestInfiniteSet", "popSmallest", "addBack", "popSmallest"], values = [[], [], [1], []]
Output: [null, 1, null, 1]
💡 Note: Initialize set with all positive integers. popSmallest() returns 1. addBack(1) puts 1 back. popSmallest() returns 1 again.
Example 2 — Multiple Pops
$ Input: operations = ["SmallestInfiniteSet", "popSmallest", "popSmallest", "addBack", "popSmallest"], values = [[], [], [], [1], []]
Output: [null, 1, 2, null, 1]
💡 Note: Pop 1, then pop 2. Add 1 back. Next pop returns 1 (smallest available).
Example 3 — No Duplicate Adds
$ Input: operations = ["SmallestInfiniteSet", "addBack", "popSmallest"], values = [[], [1], []]
Output: [null, null, 1]
💡 Note: Adding 1 when it's already in set has no effect. popSmallest() still returns 1.

Constraints

  • 1 ≤ num ≤ 1000
  • At most 1000 calls will be made in total to popSmallest and addBack.

Visualization

Tap to expand
Smallest Number in Infinite Set Operations...12345AvailablePoppedAvailableAvailableAvailableOperations: popSmallest() → 1, addBack(2), popSmallest() → 2Min Heap(returned numbers)[2]Next Counter(next new number)3Efficient: O(log n) per operation
Understanding the Visualization
1
Initial State
Set contains all positive integers [1, 2, 3, 4, 5, ...]
2
Operations
popSmallest removes and returns smallest, addBack restores numbers
3
Result
Efficient tracking of available numbers
Key Takeaway
🎯 Key Insight: Use a min-heap for returned numbers and a counter for new ones
Asked in
Google 42 Amazon 38 Apple 25 Microsoft 31
89.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen