[LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed

381. Insert Delete GetRandom O(1) - Duplicates allowed

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 removing 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 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class RandomizedCollection {
long long expire = LLONG_MIN;
unordered_map<long long, vector<int>> mp;
vector<long long> arr;
public:
RandomizedCollection() {

}

bool insert(int val) {
mp[val].push_back(arr.size());
arr.push_back(val);
return mp[val].size() == 1;
}

bool remove(int val) {
if(mp[val].empty()) return false;

int idx = mp[val].back();
arr[idx] = expire;
mp[val].pop_back();
return true;
}

int getRandom() {
while(arr.back() == expire) arr.pop_back();
long long res = expire;
while(res == expire) {
int r = rand() % arr.size();
res = arr[r];
}
return res;
}
};

/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/03/PS/LeetCode/insert-delete-getrandom-o1-duplicates-allowed/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.