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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code