A set with constant-time insert, remove and random pick. Keep values in a list and their positions in a map, and delete by swapping with the last.
▼The problem
Design a RandomizedSet with insert(val) (returns false if val is already in), remove(val) (returns false if it isn't) and getRandom() (returns any value in the set, each equally likely), each in O(1) on average.
import random
class RandomizedSet:
def __init__(self):
self.vals, self.pos = [], {}
def insert(self, x):
if x in self.pos: return False
self.pos[x] = len(self.vals)
self.vals.append(x)
return True
def remove(self, x):
if x not in self.pos: return False
i, last = self.pos[x], self.vals[-1]
self.vals[i], self.pos[last] = last, i
self.vals.pop()
del self.pos[x]
return True
def getRandom(self):
return random.choice(self.vals)Checked against a plain Python set on 5,000 random operation sequences (insert / remove return values, the contents, and that vals and pos stay consistent after every step), and 30,000 getRandom draws on {5, 8, 3} came out 10,085 / 10,027 / 9,888. src/raffle.jsx runs the same algorithm (runOps) and checks it against a JS Set at load; every list and map state on screen is that run's real state (walkthrough: insert 5, 8, 3, 6, remove 8 → [5, 6, 3] with 6 → 1). Remove is the swap-with-last: copy the last value into the removed one's slot, fix its index in the map, pop the end. Time O(1) average per operation (hash map), space O(n).
The solution
import random
class RandomizedSet:
def __init__(self):
self.vals, self.pos = [], {}
def insert(self, x):
if x in self.pos: return False
self.pos[x] = len(self.vals)
self.vals.append(x)
return True
def remove(self, x):
if x not in self.pos: return False
i, last = self.pos[x], self.vals[-1]
self.vals[i], self.pos[last] = last, i
self.vals.pop()
del self.pos[x]
return True
def getRandom(self):
return random.choice(self.vals)Transcript
Insert Delete Get Random O of One. Design a set with three moves: insert a value, remove a value, and get random, which returns any value in the set, each equally likely. All three should take constant time on average.
Say the set holds five, eight and three. Inserting five again changes nothing; it's already in. Get random should return each of the three about a third of the time.
A hash set alone inserts and removes fast, but it has no positions, so a random pick means walking through it. A list alone picks a random index instantly, but removing from the middle shifts everything after it. Either way, something costs O of n.
So use both. Keep the values in a list, like raffle tickets in numbered slots, and a map from each value to its slot. Insert puts a ticket in the next slot and writes that slot down. Get random spins for a slot number and takes that ticket.
Remove is the clever part. Pulling a ticket from the middle would leave a hole. Instead, move the last ticket into the hole, update its slot in the map, then drop the end. Only the end of the list ever grows or shrinks.
In code, insert checks the map, records the next index, then appends. Remove looks up the index, copies the last value there, fixes its index, then pops and deletes. Get random picks from the list.
Let's run it. Insert five, eight, three and six: slots zero to three. Remove eight. The map says slot one. Six, the last ticket, jumps into slot one, the map now says six is at one, and the end slot closes. Get random spins over three slots and lands on slot two: three.
Each move is one map lookup plus work at the end of the list, so all three are O of one on average, with O of n space for the list and the map.
Look it up, swap with the last, then pop. That's Insert Delete Get Random.