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 object
  • bool insert(int val) - Inserts an item val into the multiset. Returns true if the item was not present, false otherwise
  • bool remove(int val) - Removes an item val from the multiset if present. Returns true if the item was present, false otherwise. If val has multiple occurrences, only remove one of them
  • int 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
RandomizedCollection - Insert/Delete/GetRandom O(1) INPUT Operations: 1. RandomizedCollection() 2. insert(1) 3. insert(1) 4. insert(2) 5. getRandom(), 6. remove(1) Data Structure Design: nums[] array: 1 1 2 idx: 0 1 2 HashMap (val --> indices set): 1 --> {0, 1} 2 --> {2} (stores all indices for each value) ALGORITHM STEPS 1 insert(val) Add val to nums[], add index to HashMap[val] set Return: true if new, else false 2 remove(val) Get any idx from HashMap[val] Swap with last element Update indices, pop last 3 getRandom() Return nums[random index] Probability ~ count (natural) 4 Why O(1)? Array: O(1) access/add/swap HashSet: O(1) add/remove/lookup Remove Example (remove 1): [1,1,2] idx=0 of val 1 Swap: [2,1,1] (swap 0 <-> 2) Pop: [2,1] Update: 2-->{0}, 1-->{1} FINAL RESULT Output Array: [null, true, false, true, 1, true, 2] Execution Trace: 1. init: [] --> null 2. insert(1): [1] --> true (new) 3. insert(1): [1,1] --> false (dup) 4. insert(2): [1,1,2] --> true 5. getRandom(): --> 1 or 2 6. remove(1): [2,1] --> true 7. getRandom(): --> 2 (50%) Prob: 1 has 1/2, 2 has 1/2 Final State: OK - O(1) All ops average O(1) time! Key Insight: Combine HashMap (value --> set of indices) with Dynamic Array for O(1) operations with duplicates. Use HashSet for indices to handle multiple occurrences. Swap-with-last trick enables O(1) removal. getRandom naturally gives probability proportional to count since duplicates appear multiple times in array. TutorialsPoint - Insert Delete GetRandom O(1) - Duplicates allowed | Hash Map + Dynamic Array Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen