Sponsored
Sponsored
In this approach, we keep track of removed numbers using a priority queue (min heap) and a set to allow efficient look-up, addition, and removal operations. The priority queue keeps the numbers in sorted order, allowing us to quickly access and remove the smallest number. The set helps us to efficiently check whether a number needs to be added back.
Time Complexity: O(log n) for both pop and add operations, where n is the size of the heap.
Space Complexity: O(n), where n is the size of the heap.
1using System;
2using System.Collections.Generic;
3
4public class SmallestInfiniteSet {
5 private SortedSet<int> set;
6 private int current;
7
8 public SmallestInfiniteSet() {
9 set = new SortedSet<int>();
10 current = 1;
11 }
12
13 public int PopSmallest() {
14 if (set.Count > 0) {
15 int smallest = set.Min;
16 set.Remove(smallest);
17 return smallest;
18 }
19 return current++;
20 }
21
22 public void AddBack(int num) {
23 if (num < current && !set.Contains(num))
24 set.Add(num);
25 }
26}
27
C# utilizes the SortedSet, which is a sort of binary search tree, to maintain elements in sorted order.
In this methodology, we use an integer array to monitor the appearance of each number and a boolean flag array to verify if a number is within the set. This leverages more direct array manipulations without complex data structures.
Time Complexity: O(1) for addBack(), O(1) for popSmallest() in average case due to direct access using index.
Space Complexity: O(n), trials with fixed space that holds states up to MAX integers.
#include <set>
using namespace std;
class SmallestInfiniteSet {
vector<bool> available;
int currentSmallest;
public:
SmallestInfiniteSet() : available(1001, true), currentSmallest(1) {}
int popSmallest() {
while (!available[currentSmallest]) currentSmallest++;
available[currentSmallest] = false;
return currentSmallest;
}
void addBack(int num) {
if (!available[num] && num < currentSmallest) currentSmallest = num;
available[num] = true;
}
};
A C++ solution that capitalizes on the efficiency of direct vector index manipulation, treating availability flags as vector elements: