Smallest Number in Infinite Set - Problem
You are tasked with implementing a data structure that manages an infinite set of positive integers [1, 2, 3, 4, 5, ...]. The challenge is to efficiently handle two key operations:
- Remove the smallest number from the set and return it
- Add a number back to the set if it's not already present
This is a classic design problem that tests your ability to choose the right data structures for optimal performance. Think about how you would maintain the "smallest available number" efficiently while supporting dynamic additions and removals.
Implement the SmallestInfiniteSet class:
SmallestInfiniteSet()- Initialize the object to contain all positive integersint popSmallest()- Remove and return the smallest integer in the setvoid addBack(int num)- Add a positive integer back into the set (only if not already present)
Key insight: You don't need to store all infinite numbers explicitly!
Input & Output
basic_operations.py โ Python
$
Input:
["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
[[], [2], [], [], [], [1], [], [], []]
โบ
Output:
[null, null, 1, 2, 3, null, 1, 4, 5]
๐ก Note:
Initialize the set with all positive integers. AddBack(2) does nothing since 2 is already in set. PopSmallest() returns 1,2,3 in sequence. AddBack(1) adds 1 back since it was removed. Next popSmallest() returns 1, then 4,5 as the sequence continues.
multiple_addbacks.py โ Python
$
Input:
["SmallestInfiniteSet", "popSmallest", "popSmallest", "addBack", "addBack", "popSmallest", "popSmallest"]
[[], [], [], [1], [2], [], []]
โบ
Output:
[null, 1, 2, null, null, 1, 2]
๐ก Note:
Pop 1 and 2, then add both back. The next pops return 1 and 2 again since they're the smallest available numbers.
no_duplicate_addback.py โ Python
$
Input:
["SmallestInfiniteSet", "addBack", "addBack", "popSmallest", "addBack", "popSmallest"]
[[], [1], [1], [], [1], []]
โบ
Output:
[null, null, null, 1, null, 2]
๐ก Note:
Multiple addBack(1) calls when 1 is already in the set have no effect. First pop returns 1, addBack(1) adds it once, second pop returns 2.
Constraints
- 1 โค num โค 1000
- At most 1000 calls will be made in total to popSmallest and addBack
- All numbers are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Books 1,2,3,4,5... are all available. Next book to give out: #1
2
Checkout Books
Give out books 1,2,3 in order. Next book to give out: #4
3
Return Book
Book #2 is returned. Add it to our 'returned books' pile
4
Next Checkout
Compare: returned book #2 vs next new book #4. Give out #2 (smaller)
Key Takeaway
๐ฏ Key Insight: We only need to track returned books (min-heap) and the next new book counter. This handles infinite sets efficiently!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code