Weighted Random Picker with Live Weight Updates
Data Structure DesignModel answerLast updated
Design a sampler that picks an index in proportion to its weight, supports weight changes, draws several distinct items, and can be seeded and tested statistically.
Weighted Picker
A game studio has k collectible types, numbered 0 to k-1. Type i has a non-negative integer rarity weight w[i]. Design a class that picks types at random in proportion to those weights.
Core requirements
Picker(w): build the internal state inO(k)time.pick(): return an indexiwith probability exactlyw[i] / sum(w). The target isO(log k)per call, using prefix sums together with a search on a random target.
Follow-ups
- Live updates. Add
update(i, delta), which addsdeltatow[i].pick()must stay atO(log k). Choose a data structure and justify it (a Fenwick tree and a segment tree are both candidates). - Distinct draws. Add
pickDistinct(t), which returnstdifferent indices. Each draw must be proportional to the current weights of the items not yet chosen. Update internal state efficiently after each draw. - Reproducibility and testing. Make the randomness seedable. Describe and write property-based tests that check the empirical distribution against the expected one within a stated tolerance. Cover these edge cases: zero weights, very large weights, all weights equal, and
k = 1.
What to cover in your answer
- The approach and why the probabilities are exact.
- Complexity of every operation.
- Behaviour for invalid input (empty list, negative resulting weight, total weight 0,
ttoo large). - Code for the full class.
Hints
Hint 1
Give every index a segment of the integer range [0, total) whose length equals its weight. If you choose a uniform integer in that range, which segment contains it?
Hint 2
A static prefix array supports binary search but needs O(k) work per update. A Fenwick tree keeps partial sums so that updates and 'find the first prefix exceeding r' both take O(log k). You can search by descending the tree bit by bit instead of nesting a binary search around prefix queries.
Hint 3
For distinct draws, temporarily set the chosen item's weight to zero via update, and restore all removed weights at the end (use try/finally). For tests, inject a seeded RNG, use integer targets rather than floats, and compare observed frequencies to expected ones within a few standard deviations.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Lay the items out on the integer line [0, total), where item i owns a block of length w[i]. Draw a uniform integer r in [0, total) and return the item whose block contains r. Blocks partition the range, and block i holds exactly w[i] integers, so Pr[i] = w[i] / total exactly. Using integers rather than random() * total avoids floating-point bias, and it stays exact for huge weights (for example 10^30) in languages with big integers.
Static version
Build prefix sums P[i] = w[0] + ... + w[i]. The answer is the smallest i with P[i] > r, found with bisect_right(P, r). Build is O(k) and each pick is O(log k). The weakness is that changing one weight shifts every later prefix, so an update costs O(k).
Follow-up 1: updates with a Fenwick tree
A Fenwick tree (binary indexed tree) stores block sums so that point update and prefix query are both O(log k). It can be built in O(k): copy the weights in, then push each node's value to its parent i + (i & -i).
Lookup uses a top-down descent instead of binary search over prefix queries (which would be O(log² k)):
- Start at
pos = 0andstep= the largest power of two<= k. - If
pos + step <= kandtree[pos + step] <= r, take the step:pos += step,r -= tree[pos]. - Halve
stepand repeat until it is 0.
At the end pos is the largest 1-indexed position whose prefix sum is <= r, so the chosen item is the 0-indexed value pos.
A segment tree has the same asymptotics, but a Fenwick tree uses about half the memory, needs less code, and has smaller constants. Prefer a segment tree only if you need operations Fenwick cannot do easily, such as range-max queries.
Zero-weight items contribute 0 to their blocks, so the <= test always skips past them and they are never returned.
Follow-up 2: distinct draws
Sequential sampling without replacement means each draw is proportional to the weights of the items still available.
- Call
pick(). - Record
(i, w[i]), then callupdate(i, -w[i])soicannot be chosen again. - After
tdraws, restore every removed weight so the picker's state is unchanged.
Cost is O(t log k) including the restore. Put the restore in a finally block so an exception cannot leave weights zeroed. If the business rule is that picked items are consumed permanently, skip the restore.
Follow-up 3: reproducibility and tests
- Inject a
random.Random(seed)instance instead of using the global RNG, so two picker instances with the same seed produce identical sequences. - Use
randrange(total)for integer targets.
Tests worth writing:
- Reproducibility: two pickers with the same seed give the same 1000 picks.
- Validity property (hypothesis): for random weight lists with at least one positive entry, every pick is in range and never lands on a zero-weight index.
- Distribution check: draw
n = 200,000samples. For each index with expected probabilityp, require|observed - p| <= 5 * sqrt(p(1-p)/n). A 5-sigma tolerance with a fixed seed keeps the test deterministic and avoids flakiness. - Fixed cases:
[1](k = 1),[4]*10(all equal),[1, 0, 10**18, 3](zero plus huge), and a generic list. - Update test: after
update, the new distribution matches the new weights; setting a weight to 0 means it never appears. - Distinct draws: results contain no duplicates, have length
t, and the weights are identical before and after the call. Also check that the first-draw frequencies match the weights.
Code
import random
from typing import List, Optional
class Picker:
def __init__(self, w: List[int], seed: Optional[int] = None):
if not w:
raise ValueError("need at least one item")
if any(x < 0 for x in w):
raise ValueError("weights must be non-negative")
self.k = len(w)
self.w = list(w)
self.rng = random.Random(seed)
self.tree = [0] * (self.k + 1)
for i in range(1, self.k + 1): # O(k) build
self.tree[i] += self.w[i - 1]
j = i + (i & -i)
if j <= self.k:
self.tree[j] += self.tree[i]
self.total = sum(self.w)
self.top = 1
while self.top * 2 <= self.k:
self.top *= 2
def update(self, i: int, delta: int) -> None:
if not 0 <= i < self.k:
raise IndexError(i)
if self.w[i] + delta < 0:
raise ValueError("weight cannot become negative")
self.w[i] += delta
self.total += delta
j = i + 1
while j <= self.k:
self.tree[j] += delta
j += j & -j
def _find(self, r: int) -> int:
pos, step = 0, self.top
while step:
nxt = pos + step
if nxt <= self.k and self.tree[nxt] <= r:
pos = nxt
r -= self.tree[nxt]
step >>= 1
return pos # 0-indexed answer
def pick(self) -> int:
if self.total <= 0:
raise ValueError("total weight is zero")
return self._find(self.rng.randrange(self.total))
def pick_distinct(self, t: int) -> List[int]:
if t < 0:
raise ValueError("t must be >= 0")
if t > sum(1 for x in self.w if x > 0):
raise ValueError("not enough items with positive weight")
drawn, removed = [], []
try:
for _ in range(t):
i = self.pick()
drawn.append(i)
removed.append((i, self.w[i]))
self.update(i, -self.w[i])
finally:
for i, wt in removed:
self.update(i, wt)
return drawn
Complexity
| Operation | Time | Extra space |
|---|---|---|
| Constructor | O(k) | O(k) |
pick() | O(log k) | O(1) |
update | O(log k) | O(1) |
pick_distinct(t) | O(t log k) | O(t) |
Edge cases and common mistakes
- k = 1: the descent returns 0 with no special handling.
- Total weight 0: raise an error; do not call
randrange(0). - Negative resulting weight: reject in
update, since it breaks the interval model. - t = 0: return an empty list. t larger than the count of positive weights: raise
ValueError. - Float targets:
random() * totalloses precision for large totals and biases the result. - Nesting binary search over Fenwick prefix queries: correct but
O(log² k); use the descent. - Using
<instead of<=in the descent: this can return zero-weight items. - Rejection sampling for distinct draws: retrying duplicates can become very slow when a few heavy items dominate; zeroing weights avoids this.
- Forgetting to restore weights after an exception during distinct draws.