Design a set supporting insert, delete and random selection in expected/amortized O(1) time.
Instruction: Design set semantics with hashable values, a dense array and an index map. Explain expected/amortized complexity, uniform random selection, duplicate insertion, missing deletion, empty retrieval and deletion of the last value.
Updated
Official answer
For a set of hashable values, combine a dense array with a map from value to array index. Removal replaces the deleted entry with the last one, then updates that value's index.
import random
class RandomizedSet:
def __init__(self):
self.values = []
self.positions = {}
def insert(self, value):
if value in self.positions:
return False
self.positions[value] = len(self.values)
self.values.append(value)
return True
def delete(self, value):
if value not in self.positions:
return False
index = self.positions[value]
last = self.values[-1]
self.values[index] = last
self.positions[last] = index
self.values.pop()
del self.positions[value]
return True
def get_random(self):
if not self.values:
raise IndexError('empty set')
return random.choice(self.values)
Each stored value occupies one index, so a uniform random index selects values uniformly. Deleting the last value also works. Duplicate insertion and missing deletion return False; random retrieval from an empty set raises an error. This is a set, not a multiset.
The usual O(1) claim is expected/amortized under constant-cost hashing/equality and the array/random-generator model; resizing or adversarial collisions can cost more. Space is O(n). Values must keep stable hash/equality behavior while stored. This example is not thread-safe, does not preserve insertion order after deletion, and its random generator is unsuitable for security-sensitive selection.