Weighted Random Picker with Live Weight Updates
Data Structure DesignModel answerLast updated
Build a container that returns items at random with probability proportional to their weights, supports re-weighting existing items, and keeps picks fast and memory small.
Weighted Random Picker
Design a class WeightedPicker that stores named items with positive integer weights and can return a random item, where each item's chance of being returned equals its weight divided by the sum of all weights.
Required operations
add_item(item: str, weight: int)inserts the item with the given weight. If the item is already stored, its weight is replaced by the new value (it is not added to the old one, and no duplicate entry is created).pick_item() -> strreturns one item at random, using the probabilities described above.
Constraints
- Weights are positive integers.
pick_item()should run inO(log N)time or better, whereNis the number of distinct items.- Memory use should stay low even when
Nis very large.
Example
picker = WeightedPicker()
picker.add_item("red", 1)
picker.add_item("blue", 3)
# Over many calls to pick_item():
# "red" appears about 25% of the time (1 / 4)
# "blue" appears about 75% of the time (3 / 4)
What to discuss
- What should
pick_item()do when nothing has been added? - Suppose the workload has many more
add_itemcalls thanpick_itemcalls, or the reverse. How does your design behave in each case? - What should happen if a caller tries to set a weight to zero or a negative number?
Give your approach, its complexity, and working code.
Hints
Hint 1
Picture the weights laid end to end on a number line of length equal to the total. If you draw a uniform integer in [0, total), which item's segment contains it?
Hint 2
A sorted array of cumulative sums plus binary search makes picks O(log N), but changing one weight forces you to rewrite every later cumulative value. Which structure supports both prefix queries and point updates in O(log N)?
Hint 3
A Fenwick (binary indexed) tree can be searched directly: walk down by decreasing powers of two, absorbing a block whenever its sum is not larger than the remaining random value. Use a dictionary from item to position so that re-adding an item becomes a delta update.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Imagine each item owning a stretch of integer slots equal to its weight, with the stretches placed one after another. With weights red=1, blue=3 the total is 4:
slot: 0 1 2 3
owner: red blue blue blue
Draw a uniform integer r in [0, total) and return the owner of slot r. An item with weight w owns w of the total slots, so it is chosen with probability w / total, exactly as required.
The remaining question is how to find the owner of slot r quickly while still allowing updates.
Options and trade-offs
| Approach | add / update | pick | Notes |
|---|---|---|---|
| Linear scan | O(1) | O(N) | Simple but too slow |
Prefix-sum array + bisect | O(N) (later sums shift) | O(log N) | Fine if the data is nearly static |
| Prefix array rebuilt lazily | O(1) + rebuild O(N) on next pick | O(log N) | Bad if adds and picks interleave |
| Alias method | O(N) rebuild | O(1) | Best when picks dominate and weights rarely change |
| Fenwick tree | O(log N) | O(log N) | Handles any mix of adds, updates and picks |
I would choose the Fenwick tree. It satisfies the stated bound and never pays a rebuild cost, so the ratio of adds to picks does not matter.
Design
State:
names: list mapping position to item.weights: list mapping position to current weight.pos: dict mapping item to position, so "new or existing?" is an O(1) lookup.bit: 1-based Fenwick array, wherebit[i]holds the weight sum over(i - lowbit(i), i].total: running sum of all weights.
Update an existing item. Compute delta = new - old, push delta up the tree, and adjust total. Nothing is appended.
Append a new item. The new node at position i must hold the sum over (i - lowbit(i), i]. That equals weight + prefix(i-1) - prefix(i - lowbit(i)), which costs two O(log N) queries and needs no rebuild.
Pick. Draw r = randrange(total), then descend the tree. Starting at pos = 0 and trying block sizes from the largest power of two down to 1: if bit[pos+step] <= r, that entire block lies before slot r, so move pos += step and subtract the block sum from r. When the loop ends, pos is the count of items whose cumulative weight is at most the original r, which is the 0-based index of the owner.
Check with [1, 3] (tree [_, 1, 4]):
r = 0: the block of size 2 (sum 4) does not fit, the block of size 1 (sum 1) does not fit, sopos = 0and the result isred.r = 1, 2, 3: the size-1 block fits, then the remainder is too small for more, sopos = 1and the result isblue.
That is 1 of 4 outcomes for red and 3 of 4 for blue.
Code
import random
from typing import Dict, List, Optional
class WeightedPicker:
def __init__(self, rng: Optional[random.Random] = None) -> None:
self._rng = rng or random.Random()
self._names: List[str] = []
self._weights: List[int] = []
self._pos: Dict[str, int] = {}
self._bit: List[int] = [0] # 1-based Fenwick tree
self._total = 0
def _prefix(self, i: int) -> int:
s = 0
while i > 0:
s += self._bit[i]
i -= i & -i
return s
def _add_at(self, i: int, delta: int) -> None:
n = len(self._bit) - 1
while i <= n:
self._bit[i] += delta
i += i & -i
def _push(self, weight: int) -> None:
i = len(self._bit) # position of the new node
low = i & -i
node = weight + self._prefix(i - 1) - self._prefix(i - low)
self._bit.append(node)
def add_item(self, item: str, weight: int) -> None:
if weight <= 0:
raise ValueError("weight must be a positive integer")
idx = self._pos.get(item)
if idx is None:
self._pos[item] = len(self._names)
self._names.append(item)
self._weights.append(weight)
self._push(weight)
self._total += weight
else:
delta = weight - self._weights[idx]
if delta:
self._weights[idx] = weight
self._add_at(idx + 1, delta)
self._total += delta
def pick_item(self) -> str:
if not self._names:
raise IndexError("no items to pick from")
r = self._rng.randrange(self._total)
n = len(self._bit) - 1
pos = 0
step = 1 << (n.bit_length() - 1)
while step:
nxt = pos + step
if nxt <= n and self._bit[nxt] <= r:
pos = nxt
r -= self._bit[nxt]
step >>= 1
return self._names[pos]
Complexity
add_item(new or existing): O(log N).pick_item: O(log N).- Space: O(N). Per item there is one name, one weight, one dict entry and one tree integer, with no node objects or pointers.
Edge cases and decisions
- Empty picker: raise
IndexError. ReturningNonewould let bugs travel further from their cause. - Zero or negative weight: the contract says weights are positive, so reject with
ValueError. If the product wants "weight 0 means disabled", the tree already copes: a zero-weight item owns no slots and is never chosen. You would then only need to guard againsttotal == 0. - Re-adding an item: replaces the weight through a delta; never appends a duplicate.
- Single item: always returned.
- Randomness: use
randrange(total)on integers. Computingrandom() * totalwith floats can bias results or misplace boundaries when totals are large. - Testing: inject a seeded
random.Randomand check that frequencies over ~100k picks are within a small tolerance ofw / total.
Follow-ups
- Picks vastly outnumber changes: build an alias table (Vose's method) for O(1) picks at O(N) per rebuild, rebuilt lazily behind a dirty flag.
- Removing items: set the weight to zero and optionally compact once many zero entries accumulate, or swap with the last item and update both positions.
- Fractional weights: scale to integers, or use a float Fenwick tree and accept small rounding risk at boundaries.
Common mistakes
- Using a plain prefix array and not noticing that updates cost O(N).
- Off-by-one errors in the pick (using
<instead of<=, or drawing from[0, total]). - Appending duplicate entries when an item is re-added.
- Using float arithmetic to scale the random draw.