Insert Delete GetRandom O(1) - Duplicates allowed solution and explanation
9 more videos on this problem
Insert Delete Getrandom O(1) - Duplicates allowed || LeetcodePepcoding · 23:56 · 5K views
花花酱 LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed - 刷题找工作 EP58Hua Hua · 10:55 · 4K views
Leetcode 381. Insert Delete GetRandom O(1) - Duplicates Allowed| Python| LinkedIn Interview QuestionDonald Dang · 11:12 · 1K views
Insert Delete GetRandom O(1) - Duplicates allowed (Leetcode 381)Coding Interviews · 26:30 · 1K views
Facebook Coding Interview Question | Leetcode 381 | Insert Delete GetRandom O(1) - Duplicate allowedWorkWithGoogler · 17:05 · 1K views
LeetCode Question 381: Insert Delete GetRandom O(1) - Duplicates allowed (Hard)Trial & ErrCode · 7:16 · 308 views
381. Insert Delete GetRandom O(1) - Duplicates allowed | full - explainedCodingVerse · 20:32 · 238 views
Leetcode Question 381 "Insert Delete GetRandom O(1) - Duplicates allowed" in JavaGhumman Tech · 10:01 · 225 views
LeetCode 381 Insert Delete GetRandom O(1) - Duplicates allowed 【Java/Python/C++】微信flageek996FLAGeek官方频道 · 9:38 · 152 views
Leetcode Insert Delete GetRandom O(1) With/Without Duplicates |Solving AlgoPrep 151 | Nishant ChaharAlgoPrep · 14:18 · 4K views
The problem
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.
Solution
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.
import random
class RandomizedCollection:
def __init__(self):
self.lst = []
self.indices = {}
def insert(self, val: int) -> bool:
isNew = val not in self.indices
if val not in self.indices:
self.indices[val] = set()
self.indices[val].add(len(self.lst))
self.lst.append(val)
return isNew
def remove(self, val: int) -> bool:
if val not in self.indices or not self.indices[val]:
return False
remove_idx = self.indices[val].pop()
last_val = self.lst[-1]
self.lst[remove_idx] = last_val
if self.indices[last_val]:
self.indices[last_val].add(remove_idx)
self.indices[last_val].discard(len(self.lst) - 1)
self.lst.pop()
if not self.indices[val]:
del self.indices[val]
return True
def getRandom(self) -> int:
return random.choice(self.lst)import java.util.*;
public class RandomizedCollection {
private List<Integer> nums;
private Map<Integer, Set<Integer>> indices;
private Random rand;
public RandomizedCollection() {
nums = new ArrayList<>();
indices = new HashMap<>();
rand = new Random();
}
public boolean insert(int val) {
boolean contained = indices.containsKey(val);
if (!contained) indices.put(val, new LinkedHashSet<>());
indices.get(val).add(nums.size());
nums.add(val);
return !contained;
}
public boolean remove(int val) {
if (!indices.containsKey(val) || indices.get(val).isEmpty()) return false;
int removeIndex = indices.get(val).iterator().next();
indices.get(val).remove(removeIndex);
int last = nums.get(nums.size() - 1);
nums.set(removeIndex, last);
if (indices.get(last).contains(nums.size() - 1)) {
indices.get(last).remove(nums.size() - 1);
indices.get(last).add(removeIndex);
}
nums.remove(nums.size() - 1);
if (indices.get(val).isEmpty()) indices.remove(val);
return true;
}
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <cstdlib>
class RandomizedCollection {
public:
RandomizedCollection() {}
bool insert(int val) {
bool contained = indexMap.find(val) != indexMap.end();
indexMap[val].insert(nums.size());
nums.push_back(val);
return !contained;
}
bool remove(int val) {
if (indexMap.find(val) == indexMap.end() || indexMap[val].empty())
return false;
int removeIndex = *(indexMap[val].begin());
indexMap[val].erase(removeIndex);
int lastNum = nums.back();
nums[removeIndex] = lastNum;
indexMap[lastNum].insert(removeIndex);
indexMap[lastNum].erase(nums.size() - 1);
nums.pop_back();
if (indexMap[val].empty())
indexMap.erase(val);
return true;
}
int getRandom() {
int randomIndex = rand() % nums.size();
return nums[randomIndex];
}
private:
std::vector<int> nums;
std::unordered_map<int, std::unordered_set<int>> indexMap;
};class RandomizedCollection {
constructor() {
this.nums = [];
this.indices = new Map();
}
insert(val) {
const contained = this.indices.has(val);
if (!contained) this.indices.set(val, new Set());
this.indices.get(val).add(this.nums.length);
this.nums.push(val);
return !contained;
}
remove(val) {
if (!this.indices.has(val) || this.indices.get(val).size === 0) return false;
const removeIndex = [...this.indices.get(val).keys()][0];
this.indices.get(val).delete(removeIndex);
const lastVal = this.nums[this.nums.length - 1];
this.nums[removeIndex] = lastVal;
if (this.indices.get(lastVal).has(this.nums.length - 1)) {
this.indices.get(lastVal).delete(this.nums.length - 1);
this.indices.get(lastVal).add(removeIndex);
}
this.nums.pop();
if (this.indices.get(val).size === 0) this.indices.delete(val);
return true;
}
getRandom() {
const randomIndex = Math.floor(Math.random() * this.nums.length);
return this.nums[randomIndex];
}
}using System;
using System.Collections.Generic;
public class RandomizedCollection {
private List<int> nums;
private Dictionary<int, HashSet<int>> indexMap;
private Random rand;
public RandomizedCollection() {
nums = new List<int>();
indexMap = new Dictionary<int, HashSet<int>>();
rand = new Random();
}
public bool Insert(int val) {
if (!indexMap.ContainsKey(val))
indexMap[val] = new HashSet<int>();
indexMap[val].Add(nums.Count);
nums.Add(val);
return indexMap[val].Count == 1;
}
public bool Remove(int val) {
if (!indexMap.ContainsKey(val) || indexMap[val].Count == 0)
return false;
int removeIndex = indexMap[val].First();
indexMap[val].Remove(removeIndex);
int lastNum = nums[nums.Count - 1];
nums[removeIndex] = lastNum;
indexMap[lastNum].Add(removeIndex);
indexMap[lastNum].Remove(nums.Count - 1);
nums.RemoveAt(nums.Count - 1);
if (indexMap[val].Count == 0)
indexMap.Remove(val);
return true;
}
public int GetRandom() {
return nums[rand.Next(nums.Count)];
}
}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.
Time Complexity: O(1) average for all operations.
Space Complexity: O(n), where n is the number of elements in the multiset.
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 |
Frequently asked questions
Is Insert Delete GetRandom O(1) - Duplicates allowed easy or hard?
Insert Delete GetRandom O(1) - Duplicates allowed is classified as a Hard problem because it requires designing a custom data structure that maintains constant-time operations while handling duplicates. The challenge lies in correctly updating index mappings during swaps and deletions.
Insert Delete GetRandom O(1) - Duplicates allowed Python/Java solution
Implement a class that stores values in a list or array and maintains a dictionary/hash map from value to a set of indices. Python uses a list and defaultdict(set), while Java typically uses ArrayList and HashMap<Integer, Set<Integer>>. Both implementations rely on the swap-with-last trick to keep removals O(1).
How to solve Insert Delete GetRandom O(1) - Duplicates allowed in O(1)?
Store elements in a dynamic array and maintain a hash map from value to a set of indices where that value appears. Insert pushes the value into the array and records the index. Remove swaps the target element with the last array element, updates the index sets, and removes the last element. getRandom simply picks a random index from the array, giving O(1) average time for all operations.
What is the best approach for Insert Delete GetRandom O(1) - Duplicates allowed?
The best approach uses a combination of a dynamic array and a hash map that stores sets of indices for each value. The array enables O(1) random access for getRandom(), while the hash map allows constant-time lookup and updates for duplicates. Deletion is handled by swapping the target element with the last element and updating index mappings. This keeps insert, remove, and getRandom operations O(1) on average.
Is Insert Delete GetRandom O(1) - Duplicates allowed asked at Google/Amazon/Meta?
This problem or close variations frequently appear in interviews at large tech companies including Amazon, Google, and Meta. It tests data structure design, hash map usage, and the ability to maintain constant-time operations while supporting random access and duplicates.
What data structure is used in Insert Delete GetRandom O(1) - Duplicates allowed?
The solution combines a dynamic array with a hash map that maps each value to a set of indices in the array. The array enables constant-time random selection, while the hash map tracks where duplicates are stored so they can be removed efficiently.
What is the time complexity of Insert Delete GetRandom O(1) - Duplicates allowed?
The optimal design achieves O(1) average time for insert, remove, and getRandom operations. Insert appends to an array and records the index in a hash map. Remove swaps the element with the last item and updates index sets in constant time. Space complexity is O(n) because all elements and their index references must be stored.
