Insert Delete GetRandom O(1) - Duplicates allowed - Solution & Explanation
Problem Statement
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 reporting a random element.
Implement the RandomizedCollection class:
RandomizedCollection()Initializes the emptyRandomizedCollectionobject.bool insert(int val)Inserts an itemvalinto the multiset, even if the item is already present. Returnstrueif the item is not present,falseotherwise.bool remove(int val)Removes an itemvalfrom the multiset if present. Returnstrueif the item is present,falseotherwise. Note that ifvalhas 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 the 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 * 105calls in total will be made toinsert,remove, andgetRandom. - There will be at least one element in the data structure when
getRandomis called.
Approach Overview
Problem Overview: Design a data structure that supports insert(val), remove(val), and getRandom() in average O(1) time. Unlike the classic version, duplicates are allowed, and getRandom() must return elements with probability proportional to their frequency.
Approach 1: Brute Force with List Search (O(n) time, O(n) space)
Store all values in a simple list. insert is O(1) by appending to the list. getRandom is also O(1) by picking a random index. The problem appears during remove, where you must iterate through the list to find a matching value, giving O(n) time in the worst case. This approach works for small datasets but fails the constant-time requirement expected in interviews.
Approach 2: HashMap with Dynamic Array (O(1) average time, O(n) space)
Maintain two structures: a dynamic array storing all values and a hash map mapping each value to a set of indices where it appears in the array. The array allows constant-time random access for getRandom(). The hash map provides quick lookup of positions for duplicates. During insert, append the value to the array and record its index in the map.
Deletion uses a common trick: swap the element to remove with the last element in the array, then pop the last position. Update the index set of the swapped value inside the hash map. This avoids shifting elements and keeps removal O(1) on average. Because duplicates are tracked with index sets, multiple occurrences are handled cleanly.
The getRandom() operation simply generates a random index within the array bounds and returns that element. Since duplicates occupy multiple positions in the array, their probability naturally matches their frequency.
This design combines fast index access from an array with constant-time lookups from a hash table. Random selection relies on uniform index generation, a typical technique in randomized algorithms.
Recommended for interviews: Interviewers expect the hash map + dynamic array design. The brute force list demonstrates baseline understanding, but the optimized structure proves you know how to combine data structures and use the swap-with-last trick to maintain constant-time deletion.
Approach 1: Approach 1: Use HashMap with List
This approach uses a HashMap to store the indices of elements and a List to store the elements themselves. The HashMap enables quick updates for insertions and deletions, while the List ensures that we can select a random element efficiently.
We maintain a Count of all elements using a map, where each element maps to a set of indices in the List. During removal, we swap the element with the last element in the list (if not already last), update the HashMap accordingly, and remove the last entry from the list for O(1) complexity.
The Python solution uses a dictionary to keep track of indices where each value is located in the list. Insertion simply adds the value to the list and its index to the dictionary. Deletion involves swapping the element to be removed with the last element if it is not the last, then removing it efficiently. Getting a random element uses Python's built-in random.choice method for lists.
Code
Python
Java
C++
C#
JavaScript
Complexity
Time Complexity: O(1) average for all operations.
Space Complexity: O(n), where n is the number of elements in the multiset.
Approach 2: Default Approach
Try this approach in the editor →Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Use HashMap with List | Time Complexity: O(1) average for all operations. Space Complexity: O(n), where n is the number of elements in the multiset. |
| Default Approach | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| List with Linear Search | Insert O(1), Remove O(n), Random O(1) | O(n) | Simple baseline implementation or when constraints are very small |
| HashMap + Dynamic Array (Index Sets) | O(1) average for all operations | O(n) | Optimal approach for interviews and large inputs requiring constant-time operations |
Video Solution
Insert Delete Getrandom O(1) - Duplicates allowed || Leetcode • Pepcoding • 5,515 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Insert Delete GetRandom O(1) - Duplicates allowed easy or hard?
Insert Delete GetRandom O(1) - Duplicates allowed Python/Java solution
How to solve Insert Delete GetRandom O(1) - Duplicates allowed in O(1)?
What is the best approach for Insert Delete GetRandom O(1) - Duplicates allowed?
Is Insert Delete GetRandom O(1) - Duplicates allowed asked at Google/Amazon/Meta?
What data structure is used in Insert Delete GetRandom O(1) - Duplicates allowed?
What is the time complexity of Insert Delete GetRandom O(1) - Duplicates allowed?
Ready to solve this problem?
Practice Insert Delete GetRandom O(1) - Duplicates allowed with our built-in code editor and test cases.
Practice on FleetCode