# Solution For Insert Delete Getrandom O1

Problem Statement:
Implement the RandomizedSet class:

• RandomizedSet() Initializes the RandomizedSet object.
• bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
• bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
• int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

Solution:
The key to solving this problem is to store elements in a vector and use a hash table to keep track of the index of each element in the vector. The insert operation can be done in O(1) time by adding the element to the end of the vector and updating the hash table to map the element to its index in the vector. The remove operation requires us to remove an element from the vector, but removing an element from the middle of a vector requires shifting all the elements to the right of the element being removed by one position, which takes O(n) time. To avoid this, we can swap the element to be removed with the last element in the vector, and then remove the last element from the vector. This only takes O(1) time. We also need to update the hash table to map the index of the last element to the index of the removed element.

To get a random element, we generate a random index i between 0 and the size of the vector – 1, and return the element at that index in the vector. This takes O(1) time.

Here’s the implementation:

“`
class RandomizedSet {
public:
unordered_map indices;
vector elements;

``````/** Initialize your data structure here. */
RandomizedSet() {

}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (indices.count(val)) return false;
elements.push_back(val);
indices[val] = elements.size() - 1;
return true;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!indices.count(val)) return false;
int index = indices[val];
indices[elements.back()] = index; // update the index of the last element to the index of the removed element
elements[index] = elements.back(); // swap the element to be removed with the last element
elements.pop_back(); // remove the last element
indices.erase(val); // remove the index of the removed element
return true;
}

/** Get a random element from the set. */
int getRandom() {
int index = rand() % elements.size();
return elements[index];
}
``````

};

“`

Time Complexity:
– Insertion and removal of elements take O(1) time on average due to the hash table.
– Getting a random element takes O(1) time.
– Overall time complexity is O(1) for all operations.

## Step by Step Implementation For Insert Delete Getrandom O1

```/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/

class RandomizedSet {

ArrayList nums;
HashMap locs;
java.util.Random rand = new java.util.Random();

/** Initialize your data structure here. */
public RandomizedSet() {
nums = new ArrayList();
locs = new HashMap();
}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean contains = locs.containsKey(val);
if (contains) return false;
locs.put(val, nums.size());
return true;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
boolean contains = locs.containsKey(val);
if (! contains) return false;
int loc = locs.get(val);
if (loc < nums.size() - 1) {
int lastone = nums.get(nums.size() - 1);
nums.set(loc, lastone);
locs.put(lastone, loc);
}
locs.remove(val);
nums.remove(nums.size() - 1);
return true;
}

/** Get a random element from the set. */
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}```
`import random class RandomizedSet: def __init__(self): self.nums, self.pos = [], {} def insert(self, val: int) -> bool: if val not in self.pos: self.nums.append(val) self.pos[val] = len(self.nums) - 1 return True def remove(self, val: int) -> bool: if val in self.pos: idx, last = self.pos[val], self.nums[-1] self.nums[idx], self.pos[last] = last, idx self.nums.pop(); self.pos.pop(val, 0) return True def getRandom(self) -> int: return self.nums[random.randint(0, len(self.nums) - 1)]`
```/**
* Initialize your data structure here.
*/
var RandomizedSet = function() {

};

/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {

};

/**
* Removes a value from the set. Returns true if the set contained the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {

};

/**
* Get a random element from the set.
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {

};

/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/```
```class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {

}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (mp.find(val) != mp.end()) return false;
nums.emplace_back(val);
mp[val] = nums.size() - 1;
return true;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (mp.find(val) == mp.end()) return false;
int last = nums.back();
nums[mp[val]] = last;
mp[last] = mp[val];
nums.pop_back();
mp.erase(val);
return true;
}

/** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
private:
vector nums;
unordered_map mp;
};

/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/```
```public class RandomizedSet {
private HashSet nums;
private Random rand;

/** Initialize your data structure here. */
public RandomizedSet() {
nums = new HashSet<>();
rand = new Random();
}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public bool Insert(int val) {
if (nums.Contains(val)) return false;
return true;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
public bool Remove(int val) {
if (!nums.Contains(val)) return false;
nums.Remove(val);
return true;
}

/** Get a random element from the set. */
public int GetRandom() {
int index = rand.Next(nums.Count);
return nums.ElementAt(index);
}
}

/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.Insert(val);
* bool param_2 = obj.Remove(val);
* int param_3 = obj.GetRandom();
*/```

Scroll to Top

## Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]