15% off all plans & roadmaps Use code
See plansInsert Delete GetRandom O(1)
- LeetCode 380
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: The set needs insert, remove and random pick to each run in O(1) average time. Keep a dynamic array for random access and a hash map from value to index, then delete by swapping the target with the last element.
Problem
Implement the RandomizedSet class. It stores a set of integers and supports three operations. Each operation must run in average O(1) time.
RandomizedSet()creates the object.bool insert(int val)addsvalif it is not already in the set. Returnstruewhen it was added andfalsewhen it was already present.bool remove(int val)removesvalif it is in the set. Returnstruewhen it was removed andfalsewhen it was not present.int getRandom()returns one element of the current set. At least one element exists when this is called. Each element must have the same probability of being returned.
Example 1
Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] and [[], [1], [2], [2], [], [1], [2], []] Output: [null, true, false, true, 2, true, false, 2] Explanation: insert(1) returns true. remove(2) returns false because 2 is absent. insert(2) returns true, so the set holds [1, 2]. getRandom() returns either 1 or 2. remove(1) returns true, leaving [2]. insert(2) returns false because 2 is already present. getRandom() always returns 2.
Constraints
-2^31 <= val <= 2^31 - 1- At most
2 * 10^5calls will be made toinsert,remove, andgetRandom. - There will be at least one element in the data structure when
getRandomis called.
Constraints that matter
- Values span the full 32-bit signed range, so you cannot use a boolean array indexed by value. You need a hash map keyed by value.
- Up to 2 * 10^5 calls means an O(n) step per call can reach about 4 * 10^10 steps in the worst case. That is too slow.
- At least one element exists when getRandom runs, so the random index always has a non-empty range.
- Every element needs the same probability, so the random pick must be uniform over the stored slots.
Hints
Hint 1
This is a design problem.
Hint 2
Store the values in one list.
Solution
Intuition
This is a design problem. No single standard structure meets all three bounds, so you combine two structures. Pick each one to cover the other's weakness. This is the combined data structure design pattern.
Picture a row of numbered lockers and a clipboard listing each item's locker number. The row is nums, the clipboard is pos, and emptying a middle locker means moving the last item into it.
Start with what each operation needs. getRandom needs indexed access to any stored value in O(1). remove needs to find where a value lives in O(1). An array gives the first property and a hash map gives the second. A hash set alone fails getRandom, and an array alone fails remove.
The set has no order, so order does not need protecting. When you delete from the middle, you can move the last value into the hole and drop the last slot. This keeps the array dense, so every index from 0 to n - 1 is valid. A uniform random index then gives a uniform random value.
The map must follow the moved value so later lookups stay correct.
Worked example
Input: RandomizedSet, insert(10), insert(20), remove(10), getRandom() Output: [null, true, true, true, 20] Explanation: The first two inserts add 10 and 20, so the set holds both values. The remove call deletes 10, which leaves only 20. With one element left, getRandom must return 20.
Approach 1: Brute force with a plain list
Store the values in one list. insert scans the whole list to check for a duplicate, then appends. remove scans for the value, then shifts every later element one slot left. getRandom picks a random index, which is O(1) on a list.
What's slow: insert and remove both scan the list. A scan can touch all n values, and a remove also shifts up to n - 1 values. The work per call grows with the set size, so the total cost grows with n squared over the calls.
Steps
- Create an empty list in the constructor.
- In insert, return false if val is already in the list.
- Otherwise append val to the list and return true.
- In remove, search the list for val. Return false if it is missing.
- If found, delete that slot so later values shift left, and return true.
- In getRandom, pick a uniform random index and return the value stored there.
Dry run
On the example, insert(10) scans an empty list, finds nothing, and appends. The list is [10]. insert(20) scans [10], finds no 20, and appends, giving [10, 20]. remove(10) scans, finds 10 at index 0, and shifts 20 into slot 0, giving [20]. getRandom() picks index 0, which returns 20.
Complexity
| Time | O(n) for insert and remove, O(1) for getRandom |
|---|---|
| Space | O(n) |
Let n be the number of stored values. insert checks every value in the worst case before appending, so it costs O(n). remove searches up to n values and then shifts up to n - 1 values, so it also costs O(n). getRandom reads one index and does not depend on n. The list holds n values, so space is O(n).
PythonTested in our runner
from typing import List, Optional
import random
class RandomizedSet:
def __init__(self):
self.items = []
def insert(self, val: int) -> bool:
if val in self.items:
return False
self.items.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.items:
return False
self.items.remove(val)
return True
def getRandom(self) -> int:
return random.choice(self.items)JavaTested in our runner
import java.util.*;
class RandomizedSet {
private List<Integer> items;
private Random rng;
public RandomizedSet() {
items = new ArrayList<>();
rng = new Random();
}
public boolean insert(int val) {
if (items.contains(val)) {
return false;
}
items.add(val);
return true;
}
public boolean remove(int val) {
return items.remove(Integer.valueOf(val));
}
public int getRandom() {
return items.get(rng.nextInt(items.size()));
}
}C++Tested in our runner
#include <algorithm>
#include <random>
#include <vector>
class RandomizedSet {
private:
std::vector<int> items;
std::mt19937 rng{std::random_device{}()};
public:
RandomizedSet() {
}
bool insert(int val) {
if (std::find(items.begin(), items.end(), val) != items.end()) {
return false;
}
items.push_back(val);
return true;
}
bool remove(int val) {
auto it = std::find(items.begin(), items.end(), val);
if (it == items.end()) {
return false;
}
items.erase(it);
return true;
}
int getRandom() {
std::uniform_int_distribution<int> dist(0, (int)items.size() - 1);
return items[dist(rng)];
}
};JavaScriptTested in our runner
var RandomizedSet = function() {
this.items = [];
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
if (this.items.includes(val)) {
return false;
}
this.items.push(val);
return true;
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
const i = this.items.indexOf(val);
if (i === -1) {
return false;
}
this.items.splice(i, 1);
return true;
};
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
return this.items[Math.floor(Math.random() * this.items.length)];
};GoTested in our runner
import "math/rand"
type RandomizedSet struct {
items []int
}
func Constructor() RandomizedSet {
return RandomizedSet{items: []int{}}
}
func (this *RandomizedSet) insert(val int) bool {
for _, x := range this.items {
if x == val {
return false
}
}
this.items = append(this.items, val)
return true
}
func (this *RandomizedSet) remove(val int) bool {
for i, x := range this.items {
if x == val {
this.items = append(this.items[:i], this.items[i+1:]...)
return true
}
}
return false
}
func (this *RandomizedSet) getRandom() int {
return this.items[rand.Intn(len(this.items))]
}C#Tested in our runner
public class RandomizedSet {
private List<int> items;
private Random rng;
public RandomizedSet() {
items = new List<int>();
rng = new Random();
}
public bool insert(int val) {
if (items.Contains(val)) {
return false;
}
items.Add(val);
return true;
}
public bool remove(int val) {
return items.Remove(val);
}
public int getRandom() {
return items[rng.Next(items.Count)];
}
}The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: List plus hash map, swap and popOptimalDesign (General/Specific)
What's slow: the previous approach finds values by scanning the list. A scan costs O(n), and removing from the middle also shifts values.
The insight that fixes it: a set has no order, so a removal only has to fill one hole. Move the last value into the hole, then drop the last slot. A hash map from value to its index finds the hole in O(1). It also answers the duplicate check in O(1). The map must be updated for the value that moved.
Why it is correct. The two structures always agree: nums holds exactly the stored values, and pos[v] is the index where v sits in nums. Insert appends and records the new index, so the invariant holds. Remove changes only two entries: the hole gets the last value and that value's index is updated. Because the set has no order, nothing else needs to move, so the invariant survives every operation.
Steps
- In the constructor, create an empty list nums and an empty map pos from value to index.
- In insert, return false if val is a key in pos.
- Otherwise set pos[val] to the current length of nums, append val to nums, and return true.
- In remove, return false if val is not a key in pos.
- Otherwise read idx = pos[val] and last = nums[-1].
- Write last into nums[idx], set pos[last] = idx, pop the last slot of nums, and delete pos[val].
- In getRandom, pick a uniform index in [0, len(nums) - 1] and return that value.
Dry run
Trace the example. Step 1 inserts 10 at index 0. Step 2 inserts 20 at index 1. Step 3 is the removal that matters.
For remove(10), idx is 0 and last is 20. Writing 20 into slot 0 gives [20, 20]. Setting pos[20] = 0 keeps the map correct. Popping the last slot leaves [20], and deleting key 10 leaves {20: 0}.
Step 4 picks index 0, which returns 20.
| Step | Call | nums | pos | Returns |
|---|---|---|---|---|
| 0 | start | [] | {} | - |
| 1 | insert(10) | [10] | {10: 0} | true |
| 2 | insert(20) | [10, 20] | {10: 0, 20: 1} | true |
| 3 | remove(10) | [20] | {20: 0} | true |
| 4 | getRandom() | [20] | {20: 0} | 20 |
Complexity
| Time | O(1) average per operation |
|---|---|
| Space | O(n) |
Let n be the number of stored values. insert does one map lookup, one map write and one append, so each costs O(1) on average. remove does one map lookup, two writes to nums and pos, one pop and one map delete, all O(1) on average. getRandom generates one random index and reads one slot. The list and the map each hold at most n entries, so space is O(n).
PythonTested in our runner
from typing import List, Optional
import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.pos = {}
def insert(self, val: int) -> bool:
if val in self.pos:
return False
self.pos[val] = len(self.nums)
self.nums.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.pos:
return False
idx = self.pos[val]
last = self.nums[-1]
# Move the last value into the hole, then drop the last slot.
self.nums[idx] = last
self.pos[last] = idx
self.nums.pop()
del self.pos[val]
return True
def getRandom(self) -> int:
return random.choice(self.nums)JavaTested in our runner
import java.util.*;
class RandomizedSet {
private List<Integer> nums;
private Map<Integer, Integer> pos;
private Random rng;
public RandomizedSet() {
nums = new ArrayList<>();
pos = new HashMap<>();
rng = new Random();
}
public boolean insert(int val) {
if (pos.containsKey(val)) {
return false;
}
pos.put(val, nums.size());
nums.add(val);
return true;
}
public boolean remove(int val) {
if (!pos.containsKey(val)) {
return false;
}
int idx = pos.get(val);
int last = nums.get(nums.size() - 1);
nums.set(idx, last);
pos.put(last, idx);
// Pass an index here, not a value, so this removes the last slot.
nums.remove(nums.size() - 1);
pos.remove(val);
return true;
}
public int getRandom() {
return nums.get(rng.nextInt(nums.size()));
}
}C++Tested in our runner
#include <random>
#include <unordered_map>
#include <vector>
class RandomizedSet {
private:
std::vector<int> nums;
std::unordered_map<int, int> pos;
std::mt19937 rng{std::random_device{}()};
public:
RandomizedSet() {
}
bool insert(int val) {
if (pos.count(val)) {
return false;
}
pos[val] = (int)nums.size();
nums.push_back(val);
return true;
}
bool remove(int val) {
auto it = pos.find(val);
if (it == pos.end()) {
return false;
}
int idx = it->second;
int last = nums.back();
nums[idx] = last;
pos[last] = idx;
nums.pop_back();
pos.erase(val);
return true;
}
int getRandom() {
std::uniform_int_distribution<int> dist(0, (int)nums.size() - 1);
return nums[dist(rng)];
}
};JavaScriptTested in our runner
var RandomizedSet = function() {
this.nums = [];
this.pos = new Map();
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
if (this.pos.has(val)) {
return false;
}
this.pos.set(val, this.nums.length);
this.nums.push(val);
return true;
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
if (!this.pos.has(val)) {
return false;
}
const idx = this.pos.get(val);
const last = this.nums[this.nums.length - 1];
this.nums[idx] = last;
this.pos.set(last, idx);
this.nums.pop();
this.pos.delete(val);
return true;
};
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
return this.nums[Math.floor(Math.random() * this.nums.length)];
};GoTested in our runner
import "math/rand"
type RandomizedSet struct {
nums []int
pos map[int]int
}
func Constructor() RandomizedSet {
return RandomizedSet{nums: []int{}, pos: make(map[int]int)}
}
func (this *RandomizedSet) insert(val int) bool {
if _, ok := this.pos[val]; ok {
return false
}
this.pos[val] = len(this.nums)
this.nums = append(this.nums, val)
return true
}
func (this *RandomizedSet) remove(val int) bool {
idx, ok := this.pos[val]
if !ok {
return false
}
last := this.nums[len(this.nums)-1]
this.nums[idx] = last
this.pos[last] = idx
this.nums = this.nums[:len(this.nums)-1]
delete(this.pos, val)
return true
}
func (this *RandomizedSet) getRandom() int {
return this.nums[rand.Intn(len(this.nums))]
}C#Tested in our runner
public class RandomizedSet {
private List<int> nums;
private Dictionary<int, int> pos;
private Random rng;
public RandomizedSet() {
nums = new List<int>();
pos = new Dictionary<int, int>();
rng = new Random();
}
public bool insert(int val) {
if (pos.ContainsKey(val)) {
return false;
}
pos[val] = nums.Count;
nums.Add(val);
return true;
}
public bool remove(int val) {
if (!pos.ContainsKey(val)) {
return false;
}
int idx = pos[val];
int last = nums[nums.Count - 1];
nums[idx] = last;
pos[last] = idx;
nums.RemoveAt(nums.Count - 1);
pos.Remove(val);
return true;
}
public int getRandom() {
return nums[rng.Next(nums.Count)];
}
}Common mistakes
- Deleting
pos[val]before writingpos[last] = idx. Whenvalis the last element, the later write recreates the key for a removed value, so a future insert of that value returns false. Write the moved index first, then delete. - Forgetting to update
pos[last]after the swap. The moved value keeps its old index, so the next remove of that value writes into the wrong slot and corrupts the set. - Calling
nums.remove(val)orlist.removeon the value in the middle. That scans and shifts, which is O(n) per call. Swap the target with the last slot instead. - In Java, writing
nums.remove(last)with an int argument removes by index, not by value. Usenums.remove(nums.size() - 1)to pop the last slot. - Checking
val in self.numsornums.contains(val)for the duplicate test. That is a scan. The map checkval in posanswers the same question in O(1). - Building getRandom from the map, for example by iterating the dictionary or calling
random.choiceon its keys. That is O(n) and it removes the uniform index over the dense array. Sample fromnumsinstead.
Edge cases
- Remove the only element. The target and the last slot are the same, so the swap writes the value onto itself. The set becomes empty and remove returns true.
- Insert a value that is already present. insert returns false, and the list and map do not change.
- Remove a value that was never inserted. remove returns false, and nothing changes.
- Insert, remove, then insert the same value again. The second insert returns true, because the map entry was deleted.
- Use the extremes -2^31 and 2^31 - 1, plus negative values. Each fits in a 32-bit int, so no overflow happens in any of the six languages.
- Run 2 * 10^5 mixed calls. After each call, the map size must equal the list length, and every stored value must map to its exact index.
Follow-ups interviewers ask
- What if the set may hold duplicates?
- Map each value to a collection of its indices instead of one index. insert appends the value and records the new index. remove picks any index for that value, swaps it with the last slot, and updates the index collection of the moved value. Each step stays O(1) on average. You must handle the case where the removed value and the moved value are the same.
- What if removals must keep the insertion order?
- Swap and pop moves the last value into the hole, so the order breaks. A doubly linked list keeps order with O(1) removal, but it cannot reach a random position in O(1). An order-statistic tree supports ordered removal and a random pick in O(log n) each, so you give up the O(1) bound.
- What if the values do not fit in memory?
- The list and the map both hold every value, so a truly huge set needs external storage. You can keep the values in a disk-based store and keep only a partial index in memory. If you only need one random sample from a stream and never remove, reservoir sampling keeps one value in O(1) space.
Insert Delete GetRandom O(1) FAQ
What is the time complexity of Insert Delete GetRandom O(1)?
Each of the three operations runs in O(1) average time. Insert and remove each do a fixed number of hash map operations plus one list append or swap. getRandom reads one random index, so the total space is O(n) for n stored values.
Why use a hash map with an array for Insert Delete GetRandom O(1)?
The array gives O(1) random access, which getRandom needs. The hash map gives O(1) lookup of a value's position, which remove needs. A hash set alone cannot pick a random element quickly, and an array alone cannot find a value quickly.
Can Insert Delete GetRandom O(1) be solved in O(1) extra space?
No. The set must store all n values, so the storage is O(n). The map is the extra structure that makes remove O(1), and dropping it brings back the O(n) scan in remove.
Why are the bounds only average O(1)?
Hash map operations are O(1) on average. Under adversarial collisions, a lookup can degrade to O(n). The problem asks for average bounds, so a standard hash table meets the requirement.
What is the Python gotcha with this problem?
list.remove(val) looks easy, but it scans the list and shifts the values after it, which is O(n). Keep a dictionary from value to index and do the swap by hand. random.choice on a list is O(1), so getRandom stays fast.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns