Insert Delete GetRandom O(1) (LeetCode 380): Solution and Explanation
Design a RandomizedSet that supports insert, remove and getRandom, each in average O(1) time. getRandom must return every stored value with equal probability.
Intuition
No single structure does all three jobs. A hash set inserts and removes in O(1) but has no way to pick a uniformly random element without walking it. An array picks a random index in O(1) but removing from the middle shifts everything after it.
Combine them. Keep the values in an array for random access, and keep a hash map from each value to its index so any value can be found in O(1).
The only slow part left is removing from the middle of the array. The order of a set does not matter, so there is no need to shift. Copy the last value into the hole, update that value's index in the map, and pop the tail. Popping the end of an array is O(1).
Approach: Array + hash map, swap with last
- Keep
vals, an array of the stored values, andpos, a map from each value to its index invals. insert(val): ifvalis inpos, return false. Otherwise setpos[val] = len(vals), appendval, and return true.remove(val): ifvalis not inpos, return false. Otherwise leti = pos[val]andlast = vals[-1]. Setvals[i] = lastandpos[last] = i, pop the tail, deletepos[val], and return true.getRandom(): returnvals[random index].
Step-by-step example
insert 10, 20, 30, 40, then remove(20), remove(10), insert(50)
- After four inserts, vals = [10, 20, 30, 40] and pos = {10: 0, 20: 1, 30: 2, 40: 3}.
- remove(20): pos[20] = 1. The last value is 40, so copy it into index 1 and set pos[40] = 1. Pop the tail and delete 20. Now vals = [10, 40, 30].
- remove(10): pos[10] = 0. The last value is 30, so it moves to index 0 and pos[30] = 0. After the pop, vals = [30, 40].
- insert(50) appends at index 2. Every call returned true, and no element was ever shifted.
Code: Python, Java, C++
1import random
2
3class RandomizedSet:
4 def __init__(self):
5 self.vals = []
6 self.pos = {}
7
8 def insert(self, val: int) -> bool:
9 if val in self.pos:
10 return False
11 self.pos[val] = len(self.vals)
12 self.vals.append(val)
13 return True
14
15 def remove(self, val: int) -> bool:
16 if val not in self.pos:
17 return False
18 i = self.pos[val]
19 last = self.vals[-1]
20 self.vals[i] = last
21 self.pos[last] = i
22 self.vals.pop()
23 del self.pos[val]
24 return True
25
26 def getRandom(self) -> int:
27 return random.choice(self.vals)1class RandomizedSet {
2 private List<Integer> vals;
3 private Map<Integer, Integer> pos;
4 private Random rand = new Random();
5
6 public RandomizedSet() {
7 vals = new ArrayList<>();
8 pos = new HashMap<>();
9 }
10
11 public boolean insert(int val) {
12 if (pos.containsKey(val)) {
13 return false;
14 }
15 pos.put(val, vals.size());
16 vals.add(val);
17 return true;
18 }
19
20 public boolean remove(int val) {
21 if (!pos.containsKey(val)) {
22 return false;
23 }
24 int i = pos.get(val);
25 int last = vals.get(vals.size() - 1);
26 vals.set(i, last);
27 pos.put(last, i);
28 vals.remove(vals.size() - 1);
29 pos.remove(val);
30 return true;
31 }
32
33 public int getRandom() {
34 return vals.get(rand.nextInt(vals.size()));
35 }
36}1class RandomizedSet {
2public:
3 vector<int> vals;
4 unordered_map<int, int> pos;
5
6 RandomizedSet() {}
7
8 bool insert(int val) {
9 if (pos.count(val)) {
10 return false;
11 }
12 pos[val] = vals.size();
13 vals.push_back(val);
14 return true;
15 }
16
17 bool remove(int val) {
18 if (!pos.count(val)) {
19 return false;
20 }
21 int i = pos[val];
22 int last = vals.back();
23 vals[i] = last;
24 pos[last] = i;
25 vals.pop_back();
26 pos.erase(val);
27 return true;
28 }
29
30 int getRandom() {
31 return vals[rand() % vals.size()];
32 }
33};Time and space complexity
O(1) average per operation
Each operation does a constant number of hash map lookups and writes plus array access at an index or at the end.
O(n)
The array and the map each hold one entry per stored value.
Other approaches
Hash set only (time O(n) for getRandom, space O(n))
Insert and remove are O(1), but getRandom has to copy or walk the set to reach a random position, which is O(n) per call.
Array only (time O(n) for insert and remove, space O(n))
getRandom is O(1), but checking membership and removing both need a linear scan and a shift.
Common mistakes
- Deleting
pos[val]before updatingpos[last]. Whenvalis the last value itself, the order matters: writepos[last] = ifirst, then deletepos[val], or the stale entry survives. - Forgetting to update the moved value's index, which leaves the map pointing at a slot that was popped.
- Calling
list.remove(val)in Python orsplicein JavaScript, which shifts elements and makes remove O(n). - In Java, calling
vals.remove(i)with anIntegerobject instead of anintindex removes by value, not by position.
Frequently asked questions
Why move the last element instead of deleting in place?
Deleting from the middle of an array shifts every later element, which is O(n). A set has no order to preserve, so overwriting the hole with the last element and popping the end keeps remove at O(1).
Does this still work when the removed value is the last one?
Yes. The last value is copied onto itself, its index is written back unchanged, and then the tail is popped and the key deleted. The order of those writes is what makes this case safe.
How do the Codemia tests check a random function?
They only call getRandom when the set holds exactly one element, so the correct answer is that element. A real uniform pick still passes, because with one element every pick gives the same value.
What is the time complexity of each operation?
O(1) on average. Hash map operations are average O(1), and the array is only read by index or changed at its end.