# Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution

Here, We see Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.

Implement the RandomizedCollection class:

• RandomizedCollection() Initializes the empty RandomizedCollection object.
• bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.
• bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
• int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains.

You must implement the functions of the class such that each function works on average O(1) time complexity.

Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.

Example 1:
Input [“RandomizedCollection”, “insert”, “insert”, “insert”, “getRandom”, “remove”, “getRandom”] [[], [1], [1], [2], [], [1], []]
Output [null, true, false, true, 2, true, 1]

Explanation RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1); // return true since the collection does not contain 1.
// Inserts 1 into the collection.
randomizedCollection.insert(1); // return false since the collection contains 1.
// Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2); // return true since the collection does not contain 2.
// Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom(); // getRandom should:
// – return 1 with probability 2/3, or
// – return 2 with probability 1/3.
randomizedCollection.remove(1); // return true since the collection contains 1.
// Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.

## Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution C++

class RandomizedCollection {
public:
RandomizedCollection() {

}

bool insert(int val) {
bool ans = indices.find(val) == indices.end();
indices[val].insert(values.size());
values.push_back(val);
return ans;
}

bool remove(int val) {
if (indices.find(val) != indices.end()) {
int i = *indices[val].begin();
if (indices[val].size() == 1) {
indices.erase(val);
} else {
indices[val].erase(indices[val].begin());
}
if (i < values.size() - 1) {
values[i] = values.back();
indices[values[i]].erase(values.size() - 1);
indices[values[i]].insert(i);
}
values.pop_back();
return true;
}
return false;
}

int getRandom() {
return values[rand() % values.size()];
}
private:
unordered_map<int, unordered_set<int>> indices;
vector<int> values;
};Code language: PHP (php)

## Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution Java

class RandomizedCollection {

List<Integer> nums;
Map<Integer, Set<Integer>> idxMap;
Random random;

public RandomizedCollection() {
nums = new ArrayList<>();
idxMap = new HashMap<>();
random = new Random();
}

public boolean insert(int val) {
boolean response = !idxMap.containsKey(val);
if (response) {
idxMap.put(val, new HashSet<>());
}
return response;
}

public boolean remove(int val) {
if (!idxMap.containsKey(val)) {
return false;
}
Set<Integer> idxSet = idxMap.get(val);
int idxToBeRemoved = idxSet.iterator().next();
if (idxSet.size() == 1) {
idxMap.remove(val);
} else {
idxSet.remove(idxToBeRemoved);
}
int lastIdx = nums.size() - 1;
if (idxToBeRemoved != lastIdx) {
int lastVal = nums.get(lastIdx);
Set<Integer> lastIdxSet = idxMap.get(lastVal);
lastIdxSet.remove(lastIdx);
nums.set(idxToBeRemoved, lastVal);
}
nums.remove(lastIdx);
return true;
}

public int getRandom() {
return nums.get(random.nextInt(nums.size()));
}
}Code language: PHP (php)

## Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution JavaScript

var RandomizedCollection = function () {
this.arr = [];
this.map = new Map();
};

RandomizedCollection.prototype.insert = function (val) {
this.arr.push(val);
if (!this.map.has(val)) {
this.map.set(val, new Set());
return true;
} else {
return false;
}
};

RandomizedCollection.prototype.remove = function (val) {
if (!this.map.has(val)) {
return false;
}
var indexes = Array.from(this.map.get(val));
var idx = indexes[0];
var n = this.arr.length;
var last = this.arr[n - 1];
[this.arr[idx], this.arr[n - 1]] = [this.arr[n - 1], this.arr[idx]];
this.arr.pop();
this.map.get(val).delete(idx);
if (idx !== n - 1) {
this.map.get(last).delete(n - 1);
}
if (this.map.get(val).size === 0) {
this.map.delete(val);
}
return true;
};

RandomizedCollection.prototype.getRandom = function () {
var n = this.arr.length;
var idx = Math.floor(Math.random() * n);
return this.arr[idx];
};Code language: JavaScript (javascript)

## Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution Python

class RandomizedCollection:

def __init__(self):
self.nums = []
self.d = defaultdict(set)

def insert(self, val):
if val in self.d and len(self.d[val]) > 0:
res = False
else:
res = True
self.nums.append(val)
return res

def remove(self, val):
if val in self.d and len(self.d[val]) > 0:
pos = self.d[val].pop()
lpos = len(self.nums)-1
lval = self.nums[lpos]