Insert Delete GetRandom O(1) - Duplicates allowed - Problem
Design a data structure RandomizedCollection that supports inserting and removing values, as well as getting a random element from it. Duplicates are allowed in this collection.
Implement the RandomizedCollection class:
RandomizedCollection()- Initializes the empty RandomizedCollection objectbool insert(int val)- Inserts an itemvalinto the multiset. Returnstrueif the item was not present,falseotherwisebool remove(int val)- Removes an itemvalfrom the multiset if present. Returnstrueif the item was present,falseotherwise. Ifvalhas multiple occurrences, only remove one of themint getRandom()- Returns a random element from the current multiset. The probability of each element being returned is linearly related to the number of the same values the multiset contains
All functions must work in average O(1) time complexity.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"], values = [[], [1], [1], [2], [], [1], []]
›
Output:
[null, true, false, true, 1, true, 2]
💡 Note:
Initialize empty collection → insert(1) returns true (new) → insert(1) returns false (duplicate) → insert(2) returns true (new) → getRandom() returns a random element from [1,1,2] → remove(1) returns true (present) → getRandom() returns a random element from remaining collection
Example 2 — Multiple Duplicates
$
Input:
operations = ["RandomizedCollection", "insert", "insert", "insert", "getRandom"], values = [[], [4], [3], [4], []]
›
Output:
[null, true, true, false, 4]
💡 Note:
Insert 4 (new), insert 3 (new), insert 4 (duplicate). Collection has [4, 3, 4]. getRandom returns a random element with probability proportional to frequency
Example 3 — Remove from Duplicates
$
Input:
operations = ["RandomizedCollection", "insert", "insert", "remove", "getRandom"], values = [[], [10], [10], [10], []]
›
Output:
[null, true, false, true, 10]
💡 Note:
Insert 10 twice, then remove one occurrence. One 10 remains, so getRandom returns the remaining element
Constraints
- -231 ≤ val ≤ 231 - 1
- At most 2 * 105 calls will be made to insert, remove, and getRandom
- There will be at least one element in the data structure when getRandom is called
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code