Random Index Selection by Given Weights
Heaps, Sorting & SearchModel answerLast updated
Design an index sampler where each element's probability of being chosen is proportional to its assigned weight.
You are provided with an array of positive integers weights, where weights[i] represents the relative weight of index i.
Design a data structure that samples an index i with probability proportional to weights[i]. That is, the probability of selecting index i must be exactly:
$$\frac{\text{weights}[i]}{\sum_{j=0}^{n-1} \text{weights}[j]}$$
Implement a class WeightedRandomSampler:
__init__(weights: List[int]): Initializes the object with the given sequence of positive integer weights. Preprocessing should take at most $\mathcal{O}(n)$ time.pick_index() -> int: Returns a single random index in the range $[0, n-1]$. Each query should run in $\mathcal{O}(\log n)$ time.
Constraints & Rules
- $1 \le n \le 10^5$, where $n$ is the length of
weights. - $1 \le \text{weights}[i] \le 10^5$ for all $0 \le i < n$.
- The sum of all weights will fit inside a standard 64-bit integer.
pick_index()can be called up to $10^4$ times per instance.
Example
sampler = WeightedRandomSampler([1, 3])
# pick_index() should return 0 with ~25% probability and 1 with ~75% probability.
sampler = WeightedRandomSampler([1, 2, 3, 4])
# Sum = 10.
# Index 0 has probability 1/10 (10%)
# Index 1 has probability 2/10 (20%)
# Index 2 has probability 3/10 (30%)
# Index 3 has probability 4/10 (40%)
Hints
Hint 1
Consider mapping each index to a range on a continuous number line whose length corresponds to its weight.
Hint 2
What data structure lets you build cumulative ranges in linear time, and how can you quickly locate which range a random number falls into?
Hint 3
Pay close attention to boundaries: determine whether you are picking continuous floats or discrete integers, and ensure binary search bounds match that decision.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The standard approach to sampling from a non-uniform discrete distribution uses cumulative distribution functions (CDFs), implemented via a prefix sum array combined with binary search.
-
Mapping to Intervals: Imagine laying segments of length
weights[i]back-to-back along a number line starting at zero. The total length of this line equals $S = \sum \text{weights}[i]$.- Index $0$ covers range $(0, \text{prefix}[0]]$
- Index $i$ covers range $(\text{prefix}[i-1], \text{prefix}[i]]$
-
Sampling:
- Generate a uniform random integer target $t \in [1, S]$.
- Use binary search to find the smallest index $i$ such that $\text{prefix}[i] \ge t$.
Because every weight is positive, the prefix sum array is strictly increasing. This guarantees that binary search will always find a unique, valid boundary in $\mathcal{O}(\log n)$ time.
Weights: [1, 2, 3, 4]
Prefix Sums: [1, 3, 6, 10]
Target range [1, 10]:
t = 1 -> Index 0 (Range 1..1)
t = 2, 3 -> Index 1 (Range 2..3)
t = 4, 5, 6 -> Index 2 (Range 4..6)
t = 7..10 -> Index 3 (Range 7..10)
Python 3 Implementation
import bisect
import random
from typing import List
class WeightedRandomSampler:
def __init__(self, weights: List[int]):
"""
Precomputes the prefix sums of the input weights in O(N) time.
"""
self.prefix_sums = []
current_sum = 0
for w in weights:
current_sum += w
self.prefix_sums.append(current_sum)
self.total_sum = current_sum
def pick_index(self) -> int:
"""
Picks a random index in O(log N) time with probability proportional to its weight.
"""
# Draw a uniform integer target in [1, total_sum]
target = random.randint(1, self.total_sum)
# Binary search for the first prefix sum >= target
return bisect.bisect_left(self.prefix_sums, target)
Custom Binary Search (Without bisect)
If asked to implement binary search from scratch:
def pick_index(self) -> int:
target = random.randint(1, self.total_sum)
left, right = 0, len(self.prefix_sums) - 1
while left < right:
mid = (left + right) // 2
if self.prefix_sums[mid] < target:
left = mid + 1
else:
right = mid
return left
Complexity Analysis
-
Initialization ($\text{Constructor}$):
- Time Complexity: $\mathcal{O}(n)$ to compute running totals across $n$ weights.
- Space Complexity: $\mathcal{O}(n)$ auxiliary storage for the
prefix_sumsarray.
-
Query (
pick_index):- Time Complexity: $\mathcal{O}(\log n)$ per query to perform the binary search over
prefix_sums. - Space Complexity: $\mathcal{O}(1)$ auxiliary space beyond the stored data structures.
- Time Complexity: $\mathcal{O}(\log n)$ per query to perform the binary search over
Edge Cases & Pitfalls
-
Integer vs. Floating Point Randomness:
- Using floating-point values like
random.random() * total_sumintroduces floating-point precision errors (e.g., when totals exceed $2^{53}$). - Integer bounds with
random.randint(1, total_sum)paired withbisect_leftprevent off-by-one errors and maintain exact proportions.
- Using floating-point values like
-
Off-by-One Range Mismatches:
- Picking from $[0, \text{total_sum} - 1]$ requires using
bisect_rightinstead ofbisect_left. - Drawing from $[1, \text{total_sum}]$ cleanly matches
bisect_left(prefix_sums, target).
- Picking from $[0, \text{total_sum} - 1]$ requires using
Advanced Follow-ups & Optimization Options
-
$\mathcal{O}(1)$ Time Sampling (Alias Method):
- If
pick_index()is called millions of times and weights are static, Vose's Alias Method achieves $\mathcal{O}(n)$ initialization time and $\mathcal{O}(1)$ query time per sample using two probability tables.
- If
-
Dynamic Weight Updates:
- If weights can be updated dynamically at runtime, replace the prefix array with a Fenwick Tree (Binary Indexed Tree) or Segment Tree. Both updates and queries operate in $\mathcal{O}(\log n)$ time.