Weighted Random Picker for Unbounded Integer Scores
Data Structure DesignModel answerLast updated
Build a picker that returns an item with probability proportional to its weight, even when weights and their total exceed 32-bit or 64-bit limits, and discuss precision and memory trade-offs.
Weighted Random Picker
A recommendation service has a list of candidate items, each with a non-negative integer score. It must repeatedly choose one item at random, where the chance of choosing an item equals its score divided by the sum of all scores. Scores have no fixed upper bound, so a single score, or the total, can be far larger than a 32-bit or even a 64-bit integer.
Task
Design a class WeightedSampler:
WeightedSampler(items, weights)builds the picker from a list of items and a parallel list of non-negative integer weights.pick()returns one item, where itemiis returned with probability exactlyweights[i] / sum(weights).
Requirements
- Items with weight 0 must never be returned, wherever they appear in the list (first, last, or in a run).
- Behavior must be defined for invalid input: an empty list, all-zero weights, negative weights, or mismatched list lengths.
- Many
pick()calls will follow a single construction, so make picks fast.
Discussion expected
- Describe your approach and the complexity of building and picking.
- Explain what breaks when weights exceed 32-bit limits, and what you would do about it (wider integers, big integers, rescaling, floating point, logs).
- Explain how the random draw itself can introduce bias when the total is huge.
- Compare memory and speed of at least two structures, and say what you would change if weights were updated frequently.
Provide code for your chosen approach.
Hints
Hint 1
Imagine laying the items' weights end to end on a number line. Each item owns a segment whose length equals its weight. What happens if you pick a uniform point on the whole line?
Hint 2
Store inclusive prefix sums and find the segment containing a random integer r in [0, total) using binary search. Think about which bisect variant (left or right) skips zero-weight items correctly.
Hint 3
Check where precision is lost: the sums, and the random number itself. A float random in [0,1) multiplied by the total only has about 2^53 distinct outcomes, and `rand() % total` is biased. Draw an exact uniform integer instead.
Hint 4
For many picks on static weights, consider the alias method for O(1) picks. For frequently changing weights, consider a Fenwick tree with a top-down descent.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract
Before coding, I would confirm:
- Static or changing weights? Static favors prefix sums or an alias table. Frequent updates favor a Fenwick tree.
- Integer or real scores? Integers allow exact probabilities. Floats always carry rounding.
- Magnitude? One weight of 10^12 across 10^7 items gives a total near 10^19, which already overflows signed 64-bit (about 9.2 x 10^18).
- Zero and negative weights? Zero means never picked. Negative is invalid.
Contract: weights are non-negative integers, at least one is positive, and pick() returns item i with probability exactly w_i / W, where W is the total.
Core approach: prefix sums plus binary search
Place the weights end to end. With inclusive prefix sums P, item i owns the half-open interval [P[i-1], P[i]), of length exactly w_i.
- Build
Pin O(n). - To pick, draw a uniform integer
rin[0, W). - Return the item at the smallest index
iwithP[i] > r, which isbisect_right(P, r).
Correctness. r is uniform over W integers, and exactly w_i of them fall in item i's interval, so the probability is w_i / W. A zero-weight item has P[i] == P[i-1], an empty interval. bisect_right returns the first prefix strictly greater than r, so it skips any run of equal prefixes, including a zero at index 0.
Complexity: O(n) build, O(log n) per pick, O(n) space.
Alternatives and trade-offs
| Structure | Build | pick | Update | Space |
|---|---|---|---|---|
| Prefix sums + binary search | O(n) | O(log n) | O(n) | 1 number per item |
| Alias table (Vose) | O(n) | O(1) | O(n) rebuild | about 2 numbers per item |
| Fenwick tree | O(n) | O(log n) | O(log n) | 1 number per item |
- Alias method: each of
ncolumns holds a threshold and an alias. A pick chooses a column, then a biased coin decides between the column's item and its alias. Best when picks vastly outnumber rebuilds. The thresholds are usually floats, so exactness needs integer thresholds scaled byW, which makes numbersntimes larger. - Fenwick tree: supports
update(i, w)and pick by descending the tree to find the first prefix greater thanr. Use it when scores change constantly.
Precision and memory with huge weights
1. Integer overflow. A 32-bit total overflows near 2.1 x 10^9. Options, in order:
- Unsigned 64-bit (up to about 1.8 x 10^19), 8 bytes per prefix entry.
- 128-bit integers (
__int128in C++), 16 bytes per entry. - Arbitrary precision (Python
int, JavaBigInteger), variable size and each comparison costs O(b) for b bits.
2. Floating-point totals drop small items. A double has a 53-bit mantissa. If W is around 10^20, adding a weight of 1 changes nothing, so that item's interval collapses to zero width. Summation order matters too; Kahan or pairwise summation and summing small values first reduce error, but do not make it exact.
3. The random draw has limited resolution. random.random() * W yields at most 2^53 distinct values. If W > 2^53, most integers in [0, W) can never be drawn, so small items are mispicked. Also, rand() % W is biased unless W divides the generator's range. Fix: draw an exact uniform integer of full width with rejection sampling (Python random.randrange(W), Java ThreadLocalRandom.nextLong(bound) for values that fit in a long).
4. Rescaling. Dividing all weights by a common factor (for example max / 2^32) lets you use a narrower type and less memory. The cost is that small weights round to zero and ratios distort. Only do this if the product tolerates approximate proportions, and say so explicitly.
5. Real-valued or astronomically large scores. Store log w_i and normalize by the maximum so values stay in range. Alternatively use the Gumbel-max trick: return argmax(log w_i + G_i) with G_i Gumbel noise. It is O(n) per pick but never forms the overflowing sum, and it streams over items.
Code
import bisect
import random
from typing import Generic, List, Optional, Sequence, TypeVar
T = TypeVar("T")
class WeightedSampler(Generic[T]):
"""Returns items[i] with probability exactly weights[i] / sum(weights).
Weights are non-negative integers of any size. Python ints do not
overflow and randrange draws an unbiased exact integer.
"""
def __init__(self, items: Sequence[T], weights: Sequence[int],
rng: Optional[random.Random] = None) -> None:
if len(items) != len(weights):
raise ValueError("items and weights must have the same length")
self._items: List[T] = list(items)
self._prefix: List[int] = []
total = 0
for w in weights:
if not isinstance(w, int) or w < 0:
raise ValueError("weights must be non-negative integers")
total += w
self._prefix.append(total)
if total == 0:
raise ValueError("at least one weight must be positive")
self._total = total
self._rng = rng or random.Random()
def pick(self) -> T:
r = self._rng.randrange(self._total) # exact, unbiased
i = bisect.bisect_right(self._prefix, r) # first prefix > r
return self._items[i]
Edge cases
- Empty input or all zeros: raise, since no distribution exists.
- Negative weights or length mismatch: raise.
- Zero-weight items at any position are never returned.
- A single positive item is always returned.
- Weights beyond 2^64 remain exact in this implementation.
- Non-integer weights: reject, or document the precision loss.
Common mistakes
- Using
int(random.random() * W)and assuming it is uniform for largeW. - Using
rand() % W, which is biased. - Using
bisect_left, which can return a zero-weight item whenrequals a prefix value. - Summing in 32-bit or in floats and silently overflowing or losing small weights.
- Rescaling to save memory without acknowledging that small items vanish.
- Not testing the distribution: sample many times and compare frequencies, or test small cases exhaustively by enumerating every
r.