Proportional Random Index Picker with Fast Repeated Queries
Data Structure DesignModel answerLast updated
Design a class that returns a random index with probability proportional to its weight, optimized for many repeated draws after one-time setup.
Proportional Index Picker
You are given an array of positive integer weights. Build a class ProportionalPicker that, on each call, returns an index chosen at random so that index i is returned with probability weights[i] / sum(weights).
Interface
__init__(self, weights: List[int]): performs any one-time preparation on the weights.draw(self) -> int: returns one random index according to the weight distribution.
Expectations
- Setup must be fast enough for large inputs.
drawwill be called many times, so it should be asymptotically better than scanning all weights on every call.
Example
picker = ProportionalPicker([1, 3])
picker.draw() # returns 0 about 25% of the time, 1 about 75% of the time
Constraints
1 <= len(weights) <= 10^51 <= weights[i] <= 10^5drawis called at most10^4times.
Edge Cases to Consider
- Only one weight in the list.
- Totals that exceed 32-bit range (up to 10^10) in fixed-width languages.
What to Cover in Your Answer
- Your approach and why the probabilities come out exactly right.
- Time and space complexity of setup and of each draw.
- Working code.
- How you would adapt the design if weights could be updated between draws.
Hints
Hint 1
Imagine laying the weights side by side on a number line, so each index owns a stretch whose length equals its weight. What happens if you choose a uniformly random point on the whole line?
Hint 2
Precompute running totals of the weights. Because every weight is positive, those totals are strictly increasing, which means you can search them rather than scan them.
Hint 3
Be careful with off-by-one pairing: a random integer in [1, total] pairs with 'first position whose running total is >= target'. Prefer integer targets over scaling a float to avoid bias.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of the weights as consecutive segments on a number line. With weights [1, 3], index 0 owns the integer 1 and index 1 owns the integers 2 through 4. If we choose a uniform random integer in [1, total] and find which segment it falls into, each index is chosen with probability (segment length) / total, which is exactly weights[i] / sum(weights).
To locate the segment quickly:
- Setup: compute prefix sums, where
prefix[i] = weights[0] + ... + weights[i]. Since all weights are at least 1, the array is strictly increasing. - Draw: pick
target = randint(1, total), then binary search for the smallestiwithprefix[i] >= target.
For [1, 3], prefix = [1, 4]. Target 1 maps to index 0; targets 2, 3, 4 map to index 1. That gives 1/4 and 3/4.
Why It Is Correct
- Partition: index
iowns the integers in(prefix[i-1], prefix[i]], withprefix[-1] = 0. These ranges are disjoint and cover[1, total]completely. - Size: range
ihasprefix[i] - prefix[i-1] = weights[i]integers. - Uniformity: each integer in
[1, total]has probability1/total, soP(i) = weights[i] / total. - Search: the smallest
iwithprefix[i] >= targetsatisfiesprefix[i-1] < target <= prefix[i], so it is precisely the owner of the target.
Complexity
| Operation | Time | Extra space |
|---|---|---|
| Setup | O(N) | O(N) |
draw | O(log N) | O(1) |
With N = 10^5 and 10^4 draws, that is about 10^5 + 10^4 * 17 operations. The naive method rescans the weights on each call, giving up to 10^9 operations in the worst case.
Code
import bisect
import random
from itertools import accumulate
from typing import List
class ProportionalPicker:
def __init__(self, weights: List[int]):
self.prefix = list(accumulate(weights))
self.total = self.prefix[-1]
def draw(self) -> int:
target = random.randint(1, self.total) # inclusive on both ends
return bisect.bisect_left(self.prefix, target) # first prefix >= target
Common Mistakes
- Mismatched range and bisect side.
randint(1, total)pairs withbisect_left. Equivalently,randrange(total)(values 0 to total-1) pairs withbisect_right. Mixing them, such asrandint(0, total)withbisect_left, skews probabilities (index 0 gets an extra chance) or risks an out-of-range result. - Float scaling.
random.random() * totalintroduces tiny biases and ambiguity at boundaries. Integer targets are exact. - Overflow. The maximum total is 10^5 * 10^5 = 10^10, which exceeds 32 bits. Python handles this automatically, but in Java or C++ use
long/int64_t. - Linear scan per call. It works but costs O(N) per draw, which is the main thing the problem wants you to avoid.
Edge Cases
- Single weight:
prefix = [w], every target in[1, w]maps to index 0. - Equal weights: reduces to uniform sampling with no special handling.
- Highly skewed weights such as
[1, 100000]: still exact thanks to integer arithmetic.
Testing
Sample [1, 3] about 100,000 times and check you see roughly 25% zeros and 75% ones. Also test a single-element list and a case where all draws are forced (for example by seeding or mocking the random function to return 1 and total) to confirm both boundaries map to the first and last index.
Follow-ups
Dynamic weight updates. Changing one weight forces an O(N) rewrite of a prefix array. Use a Fenwick tree (binary indexed tree):
update(i, delta)takes O(log N).- Keep the total as a running counter.
- To draw, pick
targetin[1, total]and descend the tree using binary lifting: from the highest power of two downward, if the node's sum is less thantarget, subtract it and advance. This finds the first prefix>= targetin O(log N), avoiding the O(log^2 N) of a binary search that calls prefix queries. A segment tree gives the same bounds. If updates are rare, lazily rebuilding the prefix array is also reasonable.
Very large sums. If the total overflows 64 bits, use 128-bit or big integers and generate the target at the same width so it stays uniform. Alternatively, use hierarchical sampling: group weights into buckets, choose a bucket by its total, then choose within it, keeping intermediate values bounded. Normalizing to floating-point probabilities avoids overflow but adds rounding error, especially for tiny weights.
Faster draws. If draws vastly outnumber updates and you want O(1) per draw, use Walker's alias method: O(N) preprocessing, O(1) per draw, O(N) space. The trade-off is that it is more complex to implement and does not support cheap updates.
Zero weights or sparse data. If zero weights were allowed, store only the nonzero entries as parallel arrays of (original_index, prefix_sum). Space becomes O(K) for K nonzero entries and the search is O(log K).
Summary
Prefix sums turn the problem into "find which segment contains a uniform random integer," and binary search makes that fast. The details that matter are the exact pairing of inclusive range and bisect side, using integers instead of floats, and knowing that a Fenwick tree extends the idea to dynamic weights.