Leetcode 380. Insert Delete GetRandom O(1)
Your task is to design a data structure that supports all the following operations in average O(1) time complexity.
insert(val)
: Inserts an item val
into the set if not present.remove(val)
: Removes an item val
from the set if present.getRandom()
: Returns a random element from the current set of elements. Each element must have the same probability of being returned.Implement the RandomizedSet
class:
bool insert(int val)
- Inserts the item val
if it is not present. Returns true if the item was not present and false otherwise.bool remove(int val)
- Removes the item val
if it is present. Returns true if the item was present and false otherwise.int getRandom()
- Returns a random element from the current set of elements.getRandom()
is called on an empty set?
To achieve O(1) time complexity for all operations, we can use a combination of a hashmap (unordered_map
) and a dynamic array (vector
):
getRandom
.rand()
function along with the size of the vector.#include <vector>
#include <unordered_map>
#include <cstdlib>
class RandomizedSet {
private:
std::vector<int> nums;
std::unordered_map<int, int> positions;
public:
RandomizedSet() {
}
bool insert(int val) {
if (positions.find(val) != positions.end()) return false;
nums.push_back(val);
positions[val] = nums.size() - 1;
return true;
}
bool remove(int val) {
if (positions.find(val) == positions.end()) return false;
int lastElement = nums.back();
int idx = positions[val];
nums[idx] = lastElement;
positions[lastElement] = idx;
nums.pop_back();
positions.erase(val);
return true;
}
int getRandom() {
int randomIdx = rand() % nums.size();
return nums[randomIdx];
}
};
This data structure effectively combines both a hashmap and a vector to ensure that all operations meet the required average O(1) time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?