Weighted Random Item Picker from Scratch
Arrays & HashingModel answerLast updated
Implement a function that draws one item from a list at random, where each item's selection probability is proportional to its given weight.
Weighted Random Item Picker
You need to implement the following function without using any library that does the weighted sampling for you (no numpy, no random.choices):
def weighted_sample(items, weights=None):
# returns a single element from items
pass
What It Should Do
Given a list of items and a corresponding list of weights, return one item such that item i is chosen with probability proportional to weights[i]. In other words, if the weights are [1, 4, 5], the third item should come up roughly 50% of the time, the second 40%, and the first 10%.
Weights do not need to sum to 1 — your implementation must normalize internally.
Parameters
items: a list of any objects, length 1 to 10^5.weights: a list of non-negative finite numbers, same length asitems. IfNone, treat all items as equally likely.
Error Conditions
Raise ValueError when:
itemsis empty.weightsis provided but its length differs fromitems.- Any weight is negative or non-finite (NaN, infinity).
- All weights are zero (no valid distribution exists).
Randomness
Use only random.random(), which returns a float uniformly distributed over [0.0, 1.0).
Examples
items = ['A', 'B', 'C']
weights = [1, 4, 5]
# Expected long-run frequencies: A→10%, B→40%, C→50%
items = ['Red', 'Blue']
weights = [0.5, 0.5]
# Each item picked ~50% of the time
items = ['X', 'Y', 'Z']
weights = [0, 3, 0]
# Only 'Y' is ever returned
What Is Expected
- A correct implementation that satisfies the probability requirement.
- Proper input validation with
ValueErrorand a clear message. - A brief explanation of your approach, its correctness, and its time/space complexity.
- Discussion of edge cases and how you handle them.
- An answer to the follow-up: how would you redesign this for drawing thousands of samples from the same fixed distribution?
Hints
Hint 1
Lay the weights end-to-end on a number line from 0 to their total. Each item owns a segment proportional to its weight. What does it mean to 'pick a random point' on that line?
Hint 2
Once you have prefix sums, you need to find which segment a random value falls into. A binary search on the prefix array does this in O(log n) — think carefully about whether to use bisect_left or bisect_right and why the choice matters at exact boundary values.
Hint 3
You don't need to divide every weight by the total to normalize. Instead, scale your random draw up to [0, total) and search the un-normalized prefix array directly. This saves n divisions and avoids a separate accumulation of rounding error.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Prefix-Sum Interval + Binary Search
The core insight is a geometric one. Imagine a ruler of length total = sum(weights). Lay the items along it in order: item 0 occupies [0, w0), item 1 occupies [w0, w0+w1), and so on. Each item's segment is proportional to its weight, so a uniformly random point on [0, total) lands in item i's segment with exactly the right probability.
To implement this:
- Build prefix sums. For
weights = [1, 4, 5],prefix = [1, 5, 10]. Itemiowns the interval[prefix[i-1], prefix[i]). - Scale the random draw. Compute
r = random.random() * total, giving a value uniform on[0, total). No per-element division needed. - Binary-search for the segment.
bisect_right(prefix, r)returns the first index whose prefix value exceedsr, which is exactly the owning segment.
Why bisect_right and Not bisect_left
The intervals are half-open on the right: [prefix[i-1], prefix[i]). If r lands exactly on a boundary — say r = 1.0 in the example — it belongs to item 1 (B), not item 0 (A). bisect_right on a value equal to a prefix entry returns the index after that entry, putting the boundary point in the correct next segment. bisect_left would return the earlier index, misassigning boundary values.
Zero-Weight Items
A weight of 0 creates two consecutive equal prefix values, making an empty interval [p, p). bisect_right always steps past tied values, so it can never land on that index. Zero-weight items are provably never selected without any special-case code.
Floating-Point Edge Case
random.random() is strictly less than 1, but multiplying by total can round up to exactly total in rare cases. bisect_right would then return n, which is out of bounds. The fix: if idx == n, fall back to the last item with a positive weight rather than blindly clamping to n - 1 (which could itself be a zero-weight item).
Complexity
| Phase | Time | Space |
|---|---|---|
| Build prefix array | O(n) | O(n) |
| One sample | O(log n) | O(1) |
| Full standalone call | O(n) | O(n) |
For a single one-shot call, a linear scan — subtracting weights from r until it goes negative — achieves O(n) time and O(1) space, matching the setup cost with no extra memory.
Code
import random
import math
from bisect import bisect_right
from itertools import accumulate
def weighted_sample(items, weights=None):
"""Return one element of `items` with probability proportional
to `weights`. Uses only random.random() internally."""
n = len(items)
if n == 0:
raise ValueError("items must not be empty")
# Uniform distribution shortcut
if weights is None:
idx = min(int(random.random() * n), n - 1)
return items[idx]
if len(weights) != n:
raise ValueError(
f"items has {n} elements but weights has {len(weights)}"
)
for w in weights:
if not math.isfinite(w) or w < 0:
raise ValueError(
"all weights must be finite and non-negative"
)
prefix = list(accumulate(weights))
total = prefix[-1]
if total <= 0:
raise ValueError("at least one weight must be positive")
r = random.random() * total # uniform on [0, total)
idx = bisect_right(prefix, r)
# Guard against float rounding producing r == total exactly
if idx == n:
idx = max(i for i in range(n) if weights[i] > 0)
return items[idx]
Walkthrough for weights = [1, 4, 5], total = 10
prefix = [1, 5, 10]
| r | bisect_right result | item |
|---|---|---|
| 0.37 | 0 | A |
| 4.99 | 1 | B |
| 5.00 | 2 | C |
| 9.99 | 2 | C |
C covers 5 of the 10 units (50%), B covers 4 (40%), A covers 1 (10%).
Edge Cases to Name Explicitly
weights=None: uniform, handled with a direct index calculation.- Length mismatch:
ValueErrorwith both lengths in the message — easier to debug. - Negative or NaN/inf weights: rejected up front. Negative weights break prefix monotonicity; NaN poisons comparisons silently.
- All-zero total: no valid distribution; raise
ValueError. - Single item: always returned as long as its weight is positive.
- Zeros at either end: never selected, no special handling required.
Common Mistakes
- Using
bisect_left— mishandles exact boundary hits. - Normalizing weights to sum to 1 before building prefix sums — introduces extra rounding error for no benefit.
- Checking
total == 0with==on floats — use<= 0since total is a sum of non-negatives. - Clamping
idxton - 1blindly whenidx == n— could return a zero-weight item at the end.
Follow-up: Many Samples from a Fixed Distribution
Separate construction from sampling by wrapping the logic in a class. Build prefix once in O(n); each call to sample() then costs O(log n).
For very high sampling volume with a static distribution, the Vose alias method is better: O(n) setup produces two tables (prob[], alias[]), and each sample takes O(1) — pick a random column i, flip a biased coin, return i or alias[i]. This is the algorithm behind numpy.random.choice.
If the weights change frequently, a Fenwick (binary indexed) tree over the weights supports both point updates and weighted sampling in O(log n) per operation.
For drawing a batch of k samples at once, generate all k uniform values, sort them, and sweep them across the prefix array in a single O(n + k log k) pass — or just use numpy.searchsorted over a vectorized array.