Random Draw from a Mutable Membership Set in O(1)
Data Structure DesignModel answerLast updated
Build a container that registers and removes integer keys and returns a uniformly random current key, all in average constant time.
You are maintaining the set of workers who are currently free to take jobs. Workers come and go constantly, and whenever a job arrives you must hand it to one of the free workers, picked uniformly at random.
Implement a class CandidatePool (in your language, a struct/class with the same three methods):
init()— creates an empty pool.add(worker_id: int) -> bool— insertsworker_idif it is not already in the pool. ReturnsTruewhen the insert happened,Falsewhen the id was already present (nothing changes in that case).remove(worker_id: int) -> bool— deletesworker_idif present. ReturnsTruewhen it was removed,Falsewhen it was absent (nothing changes).pick() -> int— returns a currently registered id, where every registered id has the same probability of being chosen. Returns-1if the pool holds nothing.
Every one of the three operations must run in average O(1) time. You may call remove and add in any interleaving, register an id again after it was removed, and use any 32-bit signed integer as an id (negative ids are fine).
Example:
p = CandidatePool()
p.add(7) # True
p.remove(9) # False
p.add(9) # True
p.pick() # 7 or 9, 50% each
p.remove(7) # True
p.add(9) # False
p.pick() # 9
p.remove(9) # True
p.pick() # -1
Hints
Hint 1
A hash set answers membership in O(1) but can't be indexed, so it can't give you a uniform random element cheaply. A plain array indexes in O(1) but deletes from the middle in O(n). Combine them.
Hint 2
Keep the array gap-free: never leave holes. When you delete, fill the hole with the array's last element and shrink from the tail.
Hint 3
Store a map from id to its position in the array so deletion knows where the hole is. Remember to fix the moved element's recorded position, and mind the case where the removed element is itself the last one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
Two separate needs collide here. Membership questions ("is this id in the pool?") want a hash table. Uniform sampling wants positional access ("give me element at a random index"), which wants an array. Neither alone is enough:
- A hash set gives O(1) insert/delete/contains, but its iteration order or internal slots don't let you map
randrange(n)to an element, so sampling degenerates to O(n) (e.g.random.choice(list(s))). - A dynamic array gives O(1) random indexing and O(1) append-at-end, but deleting an arbitrary interior element shifts everything after it — O(n).
The resolution is to keep both, arranged so each covers the other's gap.
The design
Two fields:
items— a list containing every registered id exactly once, packed with no holes.pos— a dictionary mappingid -> index in items.
The invariant is: for every registered id c, items[pos[c]] == c, and items contains precisely the registered ids. Uniformity follows immediately — n distinct ids occupy n consecutive slots, so choosing randrange(n) picks each id with probability exactly 1/n.
- add(id): if
id in pos, returnFalse. Otherwise setpos[id] = len(items)and append. O(1) amortized. - remove(id): look up
i = pos.get(id). If missing, returnFalse. Otherwise takelast = items[-1], writeitems[i] = last, setpos[last] = i, thenitems.pop()anddel pos[id]. Order in the array carries no meaning, so overwriting the hole with the tail is safe. O(1) amortized. - pick(): if
itemsis empty return-1; else returnitems[randrange(len(items))]. O(1).
Why the invariant survives removal
The only subtle point is the sequencing inside remove, and the self-move case.
If id is not the last element, we overwrite slot i with a different id and repoint that id's map entry to i; the removed id's entry is deleted. Fine.
If id is the last element, then i == len-1, so last == id. We write the element onto itself and set pos[id] = i — a no-op write to a key we are about to delete. That is only safe because the del pos[id] happens after the pos[last] = i assignment. Reverse them and the "moved" element re-inserts a stale mapping for an id that is no longer in the array, which corrupts the invariant: a later pick can't return it, but add of that id would wrongly report "already present" and remove would try to index a slot that doesn't exist.
An explicit if i != len(items)-1 branch is equally correct and some reviewers find it clearer; the unconditional swap is shorter and has better branch behavior.
Complexity
| Operation | Time | Space |
|---|---|---|
add | O(1) average (hash lookup + amortized append) | O(1) |
remove | O(1) average (hash lookup/delete + one swap + tail pop) | O(1) |
pick | O(1) | O(1) |
Overall O(n) space for the two structures. "Average" covers hash-table collision behavior and amortized list resizing; adversarial hash collisions are theoretically O(n) but not a practical concern.
Reference implementation (Python)
import random
class CandidatePool:
def __init__(self):
self.items = [] # dense, hole-free list of ids
self.pos = {} # id -> index in self.items
def add(self, worker_id: int) -> bool:
if worker_id in self.pos:
return False
self.pos[worker_id] = len(self.items)
self.items.append(worker_id)
return True
def remove(self, worker_id: int) -> bool:
i = self.pos.get(worker_id)
if i is None:
return False
last = self.items[-1]
self.items[i] = last
self.pos[last] = i # must precede the delete below
self.items.pop()
del self.pos[worker_id]
return True
def pick(self) -> int:
if not self.items:
return -1
return self.items[random.randrange(len(self.items))]
Note pos.get returns None when absent — indices are never None, so this is unambiguous, and it avoids a double lookup.
Edge cases to mention
- Empty pool:
pickreturns-1. Since-1is a legal id under the 32-bit constraint, a caller can't distinguish "empty" from "worker -1"; call that out and follow the contract. - Duplicate add: returns
Falseand must not append — a duplicate would double that id's sampling probability. - Remove of an absent id:
False, no mutation. - Single-element pool / removing the tail: the self-move path above.
- Re-adding after removal: works naturally; the id gets a fresh index at the tail.
- Negative and extreme ids: nothing special; they are just dict keys.
Follow-ups you should be ready for
- Weighted picks. Swap
itemsfor a Fenwick tree over weights: drawrin[0, total)and descend to find the slot whose prefix sum crossesr. Adds, removes, and weight changes become O(log n); keep the swap-with-last trick so removals don't leave gaps. The alias method gives O(1) sampling but O(n) rebuilds, so it only fits static or batch-refreshed weights. - Concurrency. Guard every method with a mutex — including
pick, since a concurrent swap-and-pop can shrink the list between reading its length and indexing it. A read-write lock lets samplers run in parallel; sharding by id hash improves throughput and needs two-stage sampling (pick a shard with probabilitysize_i / total, then uniformly within it) to stay uniform. - Don't fall back to
random.choice(list(set))orrandom.choice(dict.keys())— both silently cost O(n) per pick.