Quiz
#381 Insert Delete GetRandom O(1) - Duplicates allowed
APPROACH
Build a multiset data structure that permits duplicate values, supporting insert, remove, and random retrieval each in average O(1) time.
Implement the RandomizedCollection class:
- RandomizedCollection() Constructs an empty collection.
- bool insert(int val) Adds one copy of val (duplicates allowed); returns true if val was not previously present, false if it was.
- bool remove(int val) Removes one copy of val if any exist; returns true if a copy was found and removed, false otherwise.
- int getRandom() Returns a random element with probability proportional to how many times it appears (the collection is guaranteed non-empty when called).
Each function must work on average O(1) time complexity.
Example 1:
Example 2:
What is the optimal approach for this problem?