Build a Sampler That Picks Items in Proportion to Mutable Weights
Data Structure DesignModel answerLast updated
Design a structure holding items with positive integer weights that supports insert, delete and a weight-proportional random pick, each in logarithmic time.
Weighted Lottery with Changing Membership
You are building a "lottery drawer" for a service. It stores a changing collection of entries. Each entry has a unique identifier and a positive integer weight. The drawer must support these operations:
-
insert(id, weight)adds an entry with the given weight. Ifidis already present, you decide whether to reject the call or treat it as a weight update. State your choice. -
delete(id)removes the entry if it is present. -
sample()returns one identifier at random, where the chance of returningidisweight(id) / (sum of all current weights)
Constraints
- Each operation should run in O(log n) time, where n is the number of stored entries.
- Plan for up to about 10^5 operations in total.
- A single weight can be as large as 10^9, so the total weight can exceed the range of a 32-bit integer.
- With a perfect random source,
sample()must be exactly unbiased.
Assumptions
- You have a helper
randInt(1, totalWeight)that returns a uniformly distributed integer in the inclusive range. - Identifiers come and go over time, so you must say clearly how an identifier is tied to an internal position in your structure as the set changes.
What to deliver
Describe the data structure, explain how each operation works, argue why sampling is exactly proportional, give the complexity, discuss edge cases (empty set, duplicates, missing deletes, overflow), and provide working code.
Hints
Hint 1
Imagine laying every entry's weight end to end along a number line from 1 to the total. A uniform random integer in that range lands inside exactly one entry's segment, and the segment length equals the entry's weight.
Hint 2
Finding the segment that contains a random value is a prefix-sum search: locate the first position whose running total is at least the drawn value. Which structure supports both point updates and prefix queries in O(log n)?
Hint 3
Do not shift positions when deleting. Keep a map from id to a stable slot, a reverse map from slot to id, and a pool of freed slots. A freed slot has weight 0, so it owns no integers and can never be drawn.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Contract decisions
State these first, since the problem leaves them open:
- Duplicate
insert: treat it as an update that replaces the weight. It costs the same O(log n) and is the most useful behavior. deleteof an unknown id: a no-op returningFalse.sample()on an empty set: raise an error, because the probabilities are undefined when the total is 0.- Weights: must be positive integers. Reject anything else.
Core idea
Place the weights consecutively on the integer line [1, W], where W is the total weight. Entry k owns a block of exactly weight(k) integers. Draw r = randInt(1, W) and return the entry whose block contains r, which is the first slot whose prefix sum is at least r.
So the structure must support:
- A point update of one weight.
- A search by prefix sum: find the smallest index
iwithprefix(i) >= r.
A Fenwick tree (binary indexed tree) handles both in O(log n). The search uses binary lifting and finishes in a single descent. A segment tree with a top-down walk also works, but the Fenwick tree is shorter to write.
Mapping ids to positions
Ids cannot be Fenwick indices directly because the set changes. Keep:
slot_of: a hash map from id to a 1-based slot.id_at: the reverse array from slot to id.w: the weight stored in each slot (0 when empty).free: a stack of vacated slots.
Operations:
- New insert: pop a slot from
freeif one exists, otherwise take the next never-used slot. Set the weight by adding it to the tree. - Update: add
new - oldto the existing slot. - Delete: add
-w[slot]to the tree, zero the slot, clear the reverse entry and push the slot ontofree.
Empty slots have weight 0, so they own no integers and are never returned. Nothing is ever shifted, so ids keep stable slots. Because slots are recycled, the array size is bounded by the peak number of live entries, not by the number of inserts.
Keep the capacity a power of two. When fresh slots run out, double it and rebuild the tree in O(n) from the weight array. The doublings form a geometric series, so growth is amortized O(1) per insert. Alternatively, preallocate for the 10^5 bound.
The sampling descent
Draw r uniformly from [1, total]. Set pos = 0 and loop over step = cap, cap/2, ..., 1:
- If
pos + step <= capandtree[pos + step] < r, then the target lies beyond this block. Dopos += stepandr -= tree[pos].
At the end, pos is the largest index whose prefix sum is strictly less than the original r, so the answer is slot pos + 1.
Why it is exact
- Invariant: the tree always encodes the prefix sums of
w, andtotal == sum(w). Every mutation applies the same delta to both. - Correct slot: the descent returns the first slot where the running total reaches
r. A zero-weight slot never makes the running total crossr, so it is skipped. - No bias:
ris uniform overWintegers and slotkowns exactlyweight(k)of them, soP(k) = weight(k) / W.
All arithmetic is integer. A floating-point cumulative-probability approach would introduce small biases and precision bugs with weights near 10^9, so avoid it.
Complexity
| Operation | Time | Notes |
|---|---|---|
insert (new or update) | O(log n) amortized | worst case O(log n) if preallocated |
delete | O(log n) | |
sample | O(log n) | |
| Space | O(n) | n = peak live entries |
Overflow: the largest total is about 10^5 x 10^9 = 10^14, which fits in a signed 64-bit integer. Use long long or long in C++ or Java. Python integers are unbounded.
Edge cases
- Empty set:
sample()raises an error. - Weight at most 0 or not an integer: reject.
- Re-inserting an existing id: apply
new - oldto its slot. - Deleting a missing id: no-op.
- Delete everything, then insert again: slots are reused through
free. - Single entry: always returned.
- Very skewed weights such as 1 and 10^9: still exact, since everything is integer.
Code
import random
class WeightedSampler:
def __init__(self, rand_int=None):
self.cap = 1 # power of two
self.tree = [0] * (self.cap + 1) # Fenwick tree, 1-indexed
self.w = [0] * (self.cap + 1) # weight per slot
self.id_at = [None] * (self.cap + 1)
self.slot_of = {}
self.free = []
self.next = 1 # next never-used slot
self.total = 0
self.rand = rand_int or random.randint # inclusive range
def _add(self, i, delta):
while i <= self.cap:
self.tree[i] += delta
i += i & -i
def _grow(self):
new_cap = self.cap * 2
self.w.extend([0] * (new_cap - self.cap))
self.id_at.extend([None] * (new_cap - self.cap))
self.cap = new_cap
tree = self.w[:] # linear-time Fenwick build
for i in range(1, new_cap + 1):
j = i + (i & -i)
if j <= new_cap:
tree[j] += tree[i]
self.tree = tree
def _alloc(self):
if self.free:
return self.free.pop()
if self.next > self.cap:
self._grow()
s = self.next
self.next += 1
return s
def insert(self, item_id, weight):
if not isinstance(weight, int) or weight <= 0:
raise ValueError("weight must be a positive integer")
slot = self.slot_of.get(item_id)
if slot is None:
slot = self._alloc()
self.slot_of[item_id] = slot
self.id_at[slot] = item_id
delta = weight - self.w[slot]
if delta:
self.w[slot] = weight
self._add(slot, delta)
self.total += delta
def delete(self, item_id):
slot = self.slot_of.pop(item_id, None)
if slot is None:
return False
old = self.w[slot]
self._add(slot, -old)
self.total -= old
self.w[slot] = 0
self.id_at[slot] = None
self.free.append(slot)
return True
def sample(self):
if self.total == 0:
raise IndexError("sample from empty set")
r = self.rand(1, self.total)
pos, step = 0, self.cap
while step:
nxt = pos + step
if nxt <= self.cap and self.tree[nxt] < r:
pos = nxt
r -= self.tree[nxt]
step >>= 1
return self.id_at[pos + 1]
Common mistakes
- Using floating-point cumulative probabilities, which drift and bias results.
- Compacting the array on delete by swapping or shifting, which breaks the id-to-slot mapping unless handled carefully.
- Forgetting to subtract the deleted weight from the total, so later draws land on empty slots.
- Using 32-bit integers for the tree and total.
- Leaving the duplicate-insert behavior undefined.
Alternative
A swap-with-last array plus a segment tree over the dense array avoids free slots, but it needs extra bookkeeping to move a weight on delete. The slot-and-free-list design is simpler and just as fast.