Insert Delete GetRandom O(1)
Insert Delete GetRandom O(1) is LeetCode 380 (Medium). Design a class RandomizedSet that stores distinct integers:
insert(val)addsvaland returns true, or returns false if it is already there.remove(val)deletesvaland returns true, or returns false if it is missing.getRandom()returns a stored value, each one with the same probability.
Every call must run in average O(1) time, across up to 2 × 10⁵ calls.
- -2³¹ <= val <= 2³¹ - 1
- At most 2 * 10⁵ calls will be made to insert, remove, and getRandom.
- There will be at least one element in the data structure when getRandom is called.
Intuition
No single built-in structure does all three jobs. A hash set inserts and removes in O(1) but cannot pick a uniformly random element, because it has no positions to choose from. An array can pick a random index in O(1) but needs O(n) to delete from the middle.
Keep both: an array vals of the values, and a map pos from each value to its index in vals. The map finds any value instantly. To remove one without leaving a hole, move the array's last value into its slot and pop the end. Popping the end is O(1), and the array stays gap-free, so a random index is still a fair pick.
A randomized set, with O(1) lookup and O(1) random access by position together, comes from pairing a hash map with an array and keeping the two in sync. The same swap-with-last delete shows up in any pool that must hand out random members, such as a random load balancer or a game's loot table.
Approach
Before reading on, store 1, 2 and 3, then remove 1. Which value ends up at index 0, and which map entry has to change? Then think about removing the value that is already last. Aim for average O(1) per call.
Keep an array and a value-to-index map
vals holds the values with no gaps, and pos[v] is the index of v in vals. The two must always agree: every value in vals has an entry in pos, and that entry gives its current slot.
insert: check the map, then append
If val is already a key in pos, return false. Otherwise set pos[val] = len(vals) and append val. Appending is O(1), and the index it lands on is exactly the old length of the array.
remove: fill the gap with the last value
If val is not in pos, return false. Otherwise read its index i and the last value last. Write last into vals[i] and set pos[last] = i, so the moved value's entry points at its new slot.
Pop the end, then delete the key
Pop the last slot and delete pos[val]. The delete must come after pos[last] = i. When val is itself the last value, that update writes pos[val] back, and only a later delete removes it for good.
getRandom: pick a random index
Return vals[random index]. The array has no gaps and holds each value exactly once, so every value is returned with the same probability, 1 divided by the number of values.
Code in Python, C++ and Java
vals[1] = 7 and pos[7] = 1 rewrite what is already there. This harmless step is what makes the next step's order matter.pos[7] = 1 would put 7 back into the map.vals[0] = 5 and pos[5] = 0 rewrite what is already there. This harmless step is what makes the next step's order matter.pos[5] = 0 would put 5 back into the map.Common pitfalls
Deleting the key before updating the moved value
del self.pos[val] self.pos[last] = i
self.pos[last] = i del self.pos[val]
When val is the last value, last == val, so the update re-creates the key that was just deleted. insert(5), remove(5), insert(5) then returns false, because pos still holds 5 while vals is empty.
Removing with list.remove
self.vals.remove(val)
self.vals[i] = last self.pos[last] = i self.vals.pop()
list.remove scans for the value and shifts every later element left: O(n) per call. It also changes the index of every shifted value without updating pos, so later removes read the wrong slot.
Java: vals.remove(val) removes by index
vals.remove(val); // val is an int
vals.remove(vals.size() - 1);
For a List<Integer>, remove(int) means "remove at this index", not "remove this value". remove(7) on a 3-element list throws IndexOutOfBoundsException, and remove(1) silently deletes the second slot.
Edge cases
i is 0 and last is the value itself, so it is copied onto itself, popped and deleted, leaving both structures empty.
Values are only map keys and array entries, never used as indices, so any 32-bit integer works.
Complexity
Insert Delete GetRandom O(1) FAQ
Why not pick a random key from the hash set directly?
A hash set has no positions, so the only way to pick its k-th element is to walk through k elements: O(n). Copying the keys into a list on every getRandom call is O(n) as well. The array is there to make positions exist.
Is getRandom still uniform after many removes?
Yes. After every remove the array is gap-free and holds each stored value exactly once, because the moved value fills the hole and the end is popped. So a uniform random index from 0 to n - 1 is a uniform random value. The order of vals gets shuffled by removes, but order never matters here.
What changes if duplicates are allowed?
That is problem 381. pos maps each value to a set of indices instead of one index. Remove takes any index from that set, moves the last value into it, and updates the moved value's index set in the same order as here.