LeetCode #380 Medium

Insert Delete GetRandom O(1)

Insert Delete GetRandom O(1) is LeetCode 380 (Medium). Design a class RandomizedSet that stores distinct integers:

  • insert(val) adds val and returns true, or returns false if it is already there.
  • remove(val) deletes val and 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.

Constraints
  • -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.
arrayhash-tabledesignrandomized
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1import random
▶2 
▶3 
▶4class RandomizedSet:
▶5 def __init__(self):
▶6 self.vals = []
▶7 self.pos = {}
▶8 
▶9 def insert(self, val):
▶10 if val in self.pos:
▶11 return False
▶12 self.pos[val] = len(self.vals)
▶13 self.vals.append(val)
▶14 return True
▶15 
▶16 def remove(self, val):
▶17 if val not in self.pos:
▶18 return False
▶19 i = self.pos[val]
▶20 last = self.vals[-1]
▶21 self.vals[i] = last
▶22 self.pos[last] = i
▶23 self.vals.pop()
▶24 del self.pos[val]
▶25 return True
▶26 
▶27 def getRandom(self):
▶28 return random.choice(self.vals)
valsemptyposemptyempty set
vals[]
pos{}
Two structures hold the same values. vals is a gap-free array, so a random index picks a random value. pos maps each value to its index in vals, so a value can be found without scanning.
vals10pos1→0append 1 at index 0 → true
insert1
pos[1]0
returntrue
1 is not in pos, so append it to the end of vals, the only place an array grows in O(1), and record its index 0 in pos.
vals10pos1→02 is not in pos → false
remove2
returnfalse
2 is not a key in pos, so it was never stored (or was already removed). remove returns false and touches nothing.
vals1021pos1→02→1append 2 at index 1 → true
insert2
pos[2]1
returntrue
2 is not in pos, so append it to the end of vals, the only place an array grows in O(1), and record its index 1 in pos.
vals101/2211/2pos1→02→1each of 2 slots has chance 1/2
indexrandom 0 to 1
returnany of 1, 2
Pick a random index from 0 to 1 and return the value there. vals has no gaps and holds each value once, so every value has exactly the same chance, 1/2.
vals1021pos1→02→11 sits in slot 0, last value is 2
i0slot of 1
last2at index 1
pos says 1 sits at index 0. Deleting from the middle of an array shifts everything after it, which is O(n), so instead the last value 2 will fill this slot.
vals2021pos1→02→0copy 2 into slot 0 and update its index
vals[0]2
pos[2]0
Write 2 into slot 0 and update pos[2] to 0, so the map still points at where 2 now lives. The old copy at the end is about to go.
vals20pos2→0pop the end, drop 1 from the map → true
vals[2]
returntrue
Pop the last slot, which is O(1), then delete 1 from pos. Both structures again hold exactly the same values, with no gap in vals.
vals20pos2→02 is already in pos → false
insert2
returnfalse
2 is already a key in pos, so it is already stored. A set holds each value once, so nothing changes and insert returns false.
vals201/1pos2→0one slot → returns 2
index0
return2
Pick a random index from 0 to 0 and return the value there. vals has no gaps and holds each value once, so every value has exactly the same chance, 1/1. With one value, that value is always returned.
05

Common pitfalls

Deleting the key before updating the moved value

✗ Wrong
del self.pos[val]
self.pos[last] = i
✓ Right
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

✗ Wrong
self.vals.remove(val)
✓ Right
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

✗ Wrong
vals.remove(val);  // val is an int
✓ Right
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.

06

Edge cases

Removing the only stored value

i is 0 and last is the value itself, so it is copied onto itself, popped and deleted, leaving both structures empty.

Negative values and values near 2³¹

Values are only map keys and array entries, never used as indices, so any 32-bit integer works.

07

Complexity

Time
O(1) average per call
Space
O(n)
Each call does a constant number of map lookups, one array write and at most one append or pop. Map operations are O(1) on average, which is why the bound is average and not worst case. Both structures hold one entry per stored value.
08

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.