Build a Biased Index Picker Using Cumulative Totals
Data Structure DesignModel answerLast updated
Design a class that returns an index at random with probability proportional to its weight, then explain how to make each draw fast and how to handle updates.
Biased Index Picker
You are given a list of positive integers weights. The entry weights[i] is the weight of position i. Design a class WeightedSampler that returns positions at random so that position i is returned with probability weights[i] / sum(weights).
The class must expose:
__init__(self, weights: List[int]): stores or preprocesses the weights.pick_index(self) -> int: returns one random position, following the distribution above. Each call is independent of earlier calls.
Constraints
1 <= len(weights) <= 10^41 <= weights[i] <= 10^5pick_indexis called at most10^4times.
Example
sampler = WeightedSampler([1, 3])
# pick_index() should return 0 about 25% of the time
# and 1 about 75% of the time.
Edge cases to address
- A list with a single weight.
- Large weights and totals: discuss integer overflow in languages with fixed-width integers.
What is expected
Describe your approach and justify why the resulting distribution is exactly right. Give the time and space complexity of both methods, and write working code. Be ready to discuss these follow-ups:
- How would you support changing a weight after construction?
- How would you reduce memory if the weights are extremely sparse?
- How does a single-pass, no-preprocessing method compare, and when would you prefer it?
Hints
Hint 1
Picture the weights as consecutive segments laid along a line, where segment i has length weights[i]. What happens if you choose a uniformly random point on that line?
Hint 2
Store running totals. Because every weight is positive, the totals are strictly increasing, so you can locate the segment containing a random number with binary search instead of a scan.
Hint 3
Make sure the range you draw from and the binary-search variant agree. Drawing from 1..total pairs with 'first total >= r' (bisect_left); drawing from 0..total-1 pairs with 'first total > r' (bisect_right). Mixing them skews the probabilities.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Place the weights end to end on a number line. Index i owns a segment of length weights[i]. A uniformly random point on the whole line lands in segment i with probability weights[i] / total, which is exactly the required distribution.
With integers, this means: draw a uniform integer r in [1, total], then find the segment that contains it.
Using cumulative sums
Build prefix[i] = weights[0] + ... + weights[i]. For weights = [1, 3], prefix = [1, 4]:
- index 0 owns the integer
{1} - index 1 owns the integers
{2, 3, 4}
Index i owns the integers in (prefix[i-1], prefix[i]], with prefix[-1] = 0. That interval holds exactly weights[i] integers. The intervals are disjoint and together cover [1, total], so a uniform r yields P(i) = weights[i] / total.
To find the owner, search for the smallest i with prefix[i] >= r. Since all weights are positive, prefix is strictly increasing, so binary search applies.
Code
import bisect
import random
from typing import List
class WeightedSampler:
def __init__(self, weights: List[int]):
self.prefix: List[int] = []
running = 0
for w in weights:
running += w
self.prefix.append(running)
self.total = running
def pick_index(self) -> int:
r = random.randint(1, self.total) # inclusive on both ends
return bisect.bisect_left(self.prefix, r)
Complexity
| Operation | Time | Space |
|---|---|---|
__init__ | O(n) | O(n) |
pick_index | O(log n) | O(1) extra |
With n and the number of calls both at 10^4, the work is on the order of a few hundred thousand basic operations.
The off-by-one trap
The random range and the bisect variant must match:
rin[1, total]withbisect_left: correct.rin[0, total)withbisect_right: correct.rin[0, total)withbisect_left: wrong, because every boundary shifts by one and the result is biased.
A float version (random.random() * total with bisect_right) also works, but integers avoid floating-point edge cases and are cleaner to reason about.
Edge cases
- Single weight:
prefix = [w], everyrfalls in[1, w], so the answer is always 0. No special case needed. - Overflow: the maximum total is 10^4 × 10^5 = 10^9, which fits in a signed 32-bit integer but with little room. In Java or C++ use 64-bit integers for the prefix array. Python integers do not overflow.
- Equal weights: reduces to uniform sampling and needs no special handling.
- Zero weights: excluded by the constraints. If they were allowed,
bisect_leftwould still never return a zero-width segment, since its prefix equals its predecessor's and the predecessor would be found first.
Verification
Call pick_index about 10^6 times on [1, 3] and check that the frequencies are close to 0.25 and 0.75. In unit tests, seed the random generator for reproducibility, and also test the boundaries (smallest and largest possible r) by mocking the random call.
Follow-ups
1. Weights change over time. A plain prefix array needs O(n) per update because every later total shifts. Use a Fenwick tree (binary indexed tree) over the weights:
- Update: add
new - oldat positioniin O(log n). - Pick: draw
rin[1, total], then descend the tree with binary lifting to find the smallest index whose prefix sum is at leastr, in O(log n).
A segment tree storing subtree sums gives the same bounds: go left if r <= left_sum, otherwise subtract left_sum and go right. Both use O(n) space.
2. Sparse weights. If the index space is huge and nearly all weights are zero (which requires relaxing the constraints), store only the k non-zero entries as two parallel arrays, indices and prefix. Binary search prefix, then return indices[pos]. Space becomes O(k) and a pick costs O(log k). If many weights repeat, you can also group equal weights: choose a group in proportion to weight × count, then choose uniformly inside it.
3. Single-pass alternative (weighted reservoir sampling). Scan the weights once, keeping a running total S. At index i, replace the current choice with probability w_i / S. By induction the final choice has the right distribution.
| Approach | Preprocessing | Per pick | Extra space |
|---|---|---|---|
| Single-pass reservoir | none | O(n) | O(1) |
| Prefix sums + binary search | O(n) | O(log n) | O(n) |
| Alias method | O(n) | O(1) | O(n) |
With q picks, the reservoir approach costs O(q·n), up to 10^8 here, versus O(n + q log n) for prefix sums. Reservoir sampling shines when data arrives as a stream of unknown length or you only sample once. For repeated picks on a fixed array, prefix sums are better, and if you need constant-time picks on static weights, the alias method builds its tables once and answers each pick in O(1).
Common mistakes
- Mismatching the random range and the bisect variant.
- Using a linear scan per pick, which is O(n) per call.
- Using floating-point probabilities and accumulating rounding error.
- Forgetting 64-bit totals in fixed-width languages.
- Rebuilding the whole prefix array on every update instead of using a Fenwick or segment tree.