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() could return 1 or 2 → remove(1) returns true (present) → getRandom() from remaining elements
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 has 2/3 chance for 4, 1/3 chance for 3
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 10
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
Understanding the Visualization
1
Input
Sequence of insert/remove/getRandom operations
2
Process
Maintain array + hash map for O(1) operations
3
Output
Boolean results and random elements
Key Takeaway
🎯 Key Insight: Combine array's O(1) random access with hash map's O(1) lookup to handle duplicates efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code