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 INPUT Infinite Set: [1, 2, 3, 4, 5, ...] 1 2 3 4 ... Operations: SmallestInfiniteSet() popSmallest() addBack(1) popSmallest() Input Values: [[], [], [1], []] ALGORITHM STEPS 1 Initialize Track smallest=1, use Set for added-back numbers 2 popSmallest() Check Set first, else use smallest++ (returns 1) 3 addBack(1) 1 < smallest(2), add to Set: {1} 4 popSmallest() Set has 1, remove and return it (returns 1) Data Structure: MinHeap + Pointer MinHeap smallest=2 FINAL RESULT Operation Results: SmallestInfiniteSet() --> null (initialized) popSmallest() --> 1 (removed) addBack(1) --> null (1 added back) popSmallest() --> 1 (removed again) Output Array: [null, 1, null, 1] OK - All operations complete! Key Insight: Use a pointer (smallest) to track the next integer in the infinite sequence, and a MinHeap/TreeSet to store numbers that were added back (less than current smallest). popSmallest() checks the heap first, then uses the pointer. Time: O(log n) for pop/add. Space: O(n) for added-back numbers. TutorialsPoint - Smallest Number in Infinite Set | Optimal Solution
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