O(1) Insert, Delete, and Fair Random Draw from a Live Set
Data Structure DesignModel answerLast updated
Design a data structure that supports adding, removing, and uniformly sampling integer values, all in average O(1) time with no duplicates.
O(1) Insert, Delete, and Fair Random Draw from a Live Set
A real-time pipeline tracks a changing collection of integer IDs. IDs are continuously added and expired, and at any moment the system needs to draw one ID at random — with every ID in the collection equally likely to be chosen.
Your job is to build a class LiveSet that keeps this collection and supports three operations, each running in average O(1) time:
insert(val)— addsvalto the collection if it is not already there. Returnstrueon a successful insertion,falseifvalwas already present (no change is made).remove(val)— removesvalfrom the collection if it is present. Returnstrueon a successful removal,falseifvalwas not found (no change is made).sample()— returns one element chosen uniformly at random from the current collection. Every element must have an equal chance of being returned. You may assumesample()is only called when the collection is non-empty.
The collection never holds duplicates. Inserting an existing value is always a no-op.
Example walkthrough
s = LiveSet()
s.insert(10) -> true (collection = {10})
s.remove(99) -> false (99 not present; collection = {10})
s.insert(20) -> true (collection = {10, 20})
s.sample() -> 10 or 20, each with probability 1/2
s.remove(10) -> true (collection = {20})
s.insert(20) -> false (20 already present; collection = {20})
s.sample() -> 20 (only element)
Constraints
-2^31 <= val <= 2^31 - 1- At most
2 × 10^5total calls across all three methods sample()is only called when the collection has at least one element- All three operations must run in average O(1) — solutions that scan the collection linearly for any operation are not acceptable
Hints
Hint 1
Think about which standard structure lets you pick a random element in O(1): you need index-based access, which a hash set alone cannot give you. What if you also kept the elements in a list?
Hint 2
The hard part is deletion. Removing an element from the middle of a list normally requires shifting everything after it. Is there a way to fill the gap without moving more than one element? Order in the list doesn't matter here — only membership does.
Hint 3
When you swap the target element with the last element and pop the tail, you need to update the position map too. Be careful about what happens when the element you are removing is already the last one in the list — draw it out and make sure your update order handles that case without leaving stale entries.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Paired Hash Map and Array
Why no single structure is enough
A hash set handles insert and remove in O(1) and rejects duplicates automatically. But it offers no index-based access, so drawing a uniform random element means converting it to a list first — O(n) per call.
A dynamic array makes uniform sampling trivial: pick a random index. But deleting an arbitrary element requires finding it by scanning (O(n)) and then shifting everything after it (also O(n)).
The fix is to use both together, each compensating for the other's weakness:
- An array
itemsholds the current elements in no particular order. It gives O(1) random access by index. - A hash map
index_ofmaps each value to its position initems. It gives O(1) lookup, insert, and delete.
The key insight: swap-with-last deletion
When you remove a value at position i, you would normally leave a hole. Instead:
- Overwrite slot
iwith the last element initems. - Update
index_offor that last element to point toi. - Pop the tail of
items(O(1) for a dynamic array). - Delete the removed value's entry from
index_of.
No shifting, no holes. Order inside items is arbitrary — all that matters for correctness is that every current element appears exactly once and its index_of entry is accurate.
Correctness invariant
After every operation: items holds exactly the elements of the collection, each once, and for every element x, items[index_of[x]] == x.
- insert(val): if
valis already inindex_of, returnFalse. Otherwise append toitemsand record the new tail index. Invariant holds. - remove(val): if absent, return
False. Leti = index_of[val]andlast = items[-1]. Writeitems[i] = lastandindex_of[last] = i. Then pop the tail and deleteindex_of[val]. Every remaining element still has a correct entry. - sample():
itemscontains exactlyndistinct elements. Choosing a uniform random index in[0, n)returns each with probability1/n. No rejection sampling needed.
The subtle edge case — removing the last element in the array:
When val happens to be the last element, last == val and i == len(items) - 1. The swap writes val onto itself and then index_of[last] = i re-records the same entry. This is harmless as long as you delete index_of[val] after that assignment. If you delete first and then assign, you restore a dangling entry for a value you just removed. This ordering bug is the single most common mistake in interviews.
Complexity
| Operation | Time | Space |
|---|---|---|
insert | Average O(1) | — |
remove | Average O(1) | — |
sample | O(1) | — |
| Overall | — | O(n) |
"Average" reflects expected-O(1) hash map operations and amortized-O(1) array appends. Worst-case hash collisions can degrade to O(n), but that is true of every hash-based structure.
Python implementation
import random
class LiveSet:
def __init__(self):
self.items = [] # contiguous storage enabling O(1) index access
self.index_of = {} # value -> its current index in self.items
def insert(self, val: int) -> bool:
if val in self.index_of:
return False
self.index_of[val] = len(self.items)
self.items.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.index_of:
return False
i = self.index_of[val]
last = self.items[-1]
# Plug the gap with the last element.
self.items[i] = last
self.index_of[last] = i # must happen before deleting index_of[val]
# Clean up the tail and the removed entry.
self.items.pop()
del self.index_of[val]
return True
def sample(self) -> int:
return self.items[random.randrange(len(self.items))]
Step-by-step trace of the example
| Call | Result | items | index_of |
|---|---|---|---|
insert(10) | True | [10] | {10:0} |
remove(99) | False | [10] | {10:0} |
insert(20) | True | [10, 20] | {10:0, 20:1} |
sample() | 10 or 20 | — | — |
remove(10) | True | [20] | {20:0} |
insert(20) | False | [20] | {20:0} |
sample() | 20 | — | — |
For remove(10): i = 0, last = 20. Swap gives items = [20, 20] and index_of = {10:0, 20:0}. After pop and delete: items = [20], index_of = {20:0}.
Common mistakes to avoid
random.choice(list(set))converts to a list on every call — O(n).list.remove(val)scans the list — O(n).- Lazy deletion with tombstones:
samplemust then skip over dead entries. As the live fraction shrinks, expected draws per call grows and can become unbounded without periodic compaction. - Deleting from
index_ofbefore updating the swapped element's entry whenlast == val: leaves a ghost entry.
Likely follow-up directions
- Multiset (duplicates allowed): map each value to a set of indices rather than a single index. On removal, pick any index from the set, perform the same swap, and update the displaced element's index set — remove its old tail index and add the new position
i. Handlelast == valcarefully since you're modifying the same set. - Weighted sampling: this structure no longer applies. A Fenwick tree or segment tree over cumulative weights gives O(log n) update and O(log n) sampling via binary search. If weights are static, an alias table achieves O(1) sampling after O(n) preprocessing.
- Thread safety: the swap, pop, and map-delete sequence is not atomic. A concurrent
sample()could see a duplicated tail mid-operation. Guard the compound sequence with a lock in a multi-threaded context.