Insert, delete and pick at random, all in O(1)
🌍 In real life. At a school fair, a lucky-draw box takes tickets all day: a ticket goes in when someone buys one, comes out when someone asks for a refund, and every hour a winner is drawn at random, fairly, from the tickets in the box. With thousands of tickets, each of the three must be instant.
A set adds and removes in O(1) but can't pick a random member fairly without making a list first (O(n)). A list picks at random in O(1), random.choice, but removing from the middle shifts everything (O(n)). Together, a list and a dict do all three in O(1) (LeetCode 380).
The idea in one sentence: keep the values in a list for fair random picks, and a dict from each value to its index, so a removal can find the value at once and fill its gap with the last item of the list, which never shifts anything.
Its words:
- index map:
where, value → position initems - swap with last: move the list's last value into the removed value's place, then
pop()the end in O(1) - uniform random: each value equally likely;
random.choiceon a list without gaps gives that
Step by step, removing 10 from [10, 20, 30]:
wheresays 10 is at index 0.- Take the last value, 30, off the end:
[10, 20]. - Put 30 where 10 was:
[30, 20]. - Tell
wherethat 30 now lives at index 0. Nothing else moved.
Why it is correct. Two facts stay true after every operation: items holds exactly the values in the bag, with no gaps, and where[v] is the index of v in items. Insert appends and records; remove moves exactly one value (the last) and updates its one entry. Since the list has no gaps, random.choice gives every value the same chance.
What it costs, by counting. Insert: a dict lookup, a dict write, an append: O(1) (amortised, Lesson 34.2). Remove: a dict lookup and pop, a list pop from the end, one write each: O(1). Random: O(1). Memory: O(n) for the list and the dict together. The price of the trick is that the list's order is scrambled by removals, which doesn't matter for a bag.
Design questions follow a pattern. When one structure can't do every operation fast, combine two that each do part, and keep them in step: a dict + a linked list for the LRU cache (Lesson 63.1), a dict + a list here, and a dict + groups by count for the LFU cache next.
import random
class RandomBag:
def __init__(self):
self.items = [] # the values, in no particular order
self.where = {} # value -> its index in items
def insert(self, x):
if x in self.where:
return False
self.where[x] = len(self.items)
self.items.append(x)
return True
def remove(self, x):
if x not in self.where:
return False
i = self.where.pop(x)
last = self.items.pop() # take the last value off the end
if i < len(self.items): # x wasn't the last: fill its gap
self.items[i] = last
self.where[last] = i
return True
def get_random(self):
return random.choice(self.items)
box = RandomBag()
for ticket in [101, 102, 103, 104]:
box.insert(ticket)
print(box.insert(102), box.remove(101), box.remove(999))
print(box.items, box.where)
print(box.get_random() in {102, 103, 104})Mistakes and edge cases.
- Forgetting to update the moved value's index. Without
where[last] = i, the dict still says the moved value is at the end; removing it later pops the wrong value, and the bag ends up holding a value that was removed. - Removing the last value itself. Then there is no gap to fill: the
if i < len(self.items)check skips the move. list.remove(x). It searches from the front and shifts the rest: O(n).- Picking from a set.
random.choice(list(s))builds a list every time: O(n) per pick. - Duplicates. This bag holds each value once; to allow copies, map each value to a set of indexes (LeetCode 381).
Quiz
What does this print?
import random class RandomBag: def __init__(self): self.items = [] # the values, in no particular order self.where = {} # value -> its index in items def insert(self, x): if x in self.where: return False self.where[x] = len(self.items) self.items.append(x) return True def remove(self, x): if x not in self.where: return False i = self.where.pop(x) last = self.items.pop() # take the last value off the end if i < len(self.items): # x wasn't the last: fill its gap self.items[i] = last self.where[last] = i return True def get_random(self): return random.choice(self.items) bag = RandomBag() for x in [5, 6, 7, 8]: bag.insert(x) bag.remove(6) print(bag.items, bag.where[8])Why does remove move the LAST value into the gap?
- Popping the end of a list is O(1) and shifts nothing
- The last value is always the largest
- To keep the list sorted
Why can't a set alone do get_random in O(1)?
- It has no positions, so picking a member fairly needs a list of them first, O(n)
- Sets can't hold numbers
- random doesn't work on sets
After inserting 10, 20, 30 and removing 10 and then 30, the bag should hold [20], but items is [30]. Which line is wrong?
def remove(self, x): if x not in self.where: return False i = self.where.pop(x) last = self.items.pop() if i < len(self.items): self.items[i] = last self.where[last] = len(self.items) return True
Coding tasks
Write
RandomBagwithinsert(x)andremove(x)(each returning True if the bag changed, False if not) andget_random()(a uniformly random value from the bag), all O(1).Using the same idea, write
sample_without_repeats(values, k): return k different values drawn at random fromvalues(all distinct), each draw O(1): copy the list, pick a random index, swap that value with the last one, and pop it.