Insert Delete GetRandom O(1) – Duplicates allowed – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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 emptyRandomizedCollection
object.bool insert(int val)
Inserts an itemval
into the multiset, even if the item is already present. Returnstrue
if the item is not present,false
otherwise.bool remove(int val)
Removes an itemval
from the multiset if present. Returnstrue
if the item is present,false
otherwise. Note that ifval
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
.
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.
Constraints:
-231 <= val <= 231 - 1
- At most
2 * 105
calls in total will be made toinsert
,remove
, andgetRandom
. - There will be at least one element in the data structure when
getRandom
is called.
C++ Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution
class RandomizedCollection {
public:
/** Initialize your data structure here. */
RandomizedCollection() {
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
auto result = m.find(val) == m.end();
m[val].push_back(nums.size());
nums.push_back(pair<int, int>(val, m[val].size() - 1));
return result;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
auto result = m.find(val) != m.end();
if(result)
{
auto last = nums.back();
m[last.first][last.second] = m[val].back();
nums[m[val].back()] = last;
m[val].pop_back();
if(m[val].empty()) m.erase(val);
nums.pop_back();
}
return result;
}
/** Get a random element from the collection. */
int getRandom() {
return nums[rand() % nums.size()].first;
}
private:
vector<pair<int, int>> nums;
unordered_map<int, vector<int>> m;
};
Java Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution
public class RandomizedCollection {
ArrayList<Integer> nums;
HashMap<Integer, Set<Integer>> locs;
java.util.Random rand = new java.util.Random();
/** Initialize your data structure here. */
public RandomizedCollection() {
nums = new ArrayList<Integer>();
locs = new HashMap<Integer, Set<Integer>>();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean contain = locs.containsKey(val);
if ( ! contain ) locs.put( val, new LinkedHashSet<Integer>() );
locs.get(val).add(nums.size());
nums.add(val);
return ! contain ;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
boolean contain = locs.containsKey(val);
if ( ! contain ) return false;
int loc = locs.get(val).iterator().next();
locs.get(val).remove(loc);
if (loc < nums.size() - 1 ) {
int lastone = nums.get( nums.size()-1 );
nums.set( loc , lastone );
locs.get(lastone).remove( nums.size()-1);
locs.get(lastone).add(loc);
}
nums.remove(nums.size() - 1);
if (locs.get(val).isEmpty()) locs.remove(val);
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return nums.get( rand.nextInt(nums.size()) );
}
}
Python 3 Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution
import random
class RandomizedCollection(object):
def __init__(self):
self.vals, self.idxs = [], collections.defaultdict(set)
def insert(self, val):
self.vals.append(val)
self.idxs[val].add(len(self.vals) - 1)
return len(self.idxs[val]) == 1
def remove(self, val):
if self.idxs[val]:
out, ins = self.idxs[val].pop(), self.vals[-1]
self.vals[out] = ins
if self.idxs[ins]:
self.idxs[ins].add(out)
self.idxs[ins].discard(len(self.vals) - 1)
self.vals.pop()
return True
return False
def getRandom(self):
return random.choice(self.vals)
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1