Implement Weighted Index Selector with Efficient Retrieval
Heaps, Sorting & SearchModel answerLast updated
Design a data structure that accepts an array of positive item weights and samples indices proportional to their relative weight values.
You are tasked with building a data structure that performs weighted random sampling over a set of non-negative item weights.
Given a list of positive integers weights, construct a class WeightedRandomSampler with two methods:
__init__(self, weights: List[int]): Preprocesses the weight distribution.pick_index(self) -> int: Returns an indexiin the range[0, len(weights) - 1]with probability proportional toweights[i] / total_weight.
Constraints
1 <= weights.length <= 10^51 <= weights[i] <= 10^5pick_indexwill be invoked up to10^4times per instance.
Example
sampler = WeightedRandomSampler([2, 8])
# Weight totals 10.
# Index 0 has weight 2 -> 20% selection probability.
# Index 1 has weight 8 -> 80% selection probability.
sampler.pick_index() # Might return 1
sampler.pick_index() # Might return 1
sampler.pick_index() # Might return 0
Hints
Hint 1
Think of mapping each weight to a continuous interval on a total number line equal to the sum of all weights.
Hint 2
How can prefix sums help transform individual weight ranges into sorted threshold values?
Hint 3
Once you generate a uniform random value across the total weight range, which binary search variation correctly maps that value to the appropriate interval?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
To sample indices proportional to their weights, we can picture placing each index's weight as a contiguous interval along a single number line starting from 0 up to the sum of all weights.
For instance, given weights = [2, 5, 3]:
- Sum of weights =
10 - Index
0covers interval[0, 2)(length 2) - Index
1covers interval[2, 7)(length 5) - Index
2covers interval[7, 10)(length 3)
When we pick a uniform random integer $r$ in the half-open integer range $[0, 10)$, the probability of landing inside an index's interval is proportional to that interval's length.
Algorithm Steps
-
Preprocessing (
__init__):- Construct a cumulative prefix sum array
prefix_sums. prefix_sums[i]stores the right boundary (exclusive) of the interval assigned to indexi.- For
weights = [2, 5, 3],prefix_sums = [2, 7, 10]. - Keep track of
total_weight = prefix_sums[-1].
- Construct a cumulative prefix sum array
-
Querying (
pick_index):- Draw a uniform random integer $r \in [0, \text{total_weight})$.
- Use binary search (
bisect_right) to find the first indexiwhereprefix_sums[i] > r.
Range Boundary Details
If $r = 2$ in our example:
- Index 0 occupies ${0, 1}$
- Index 1 occupies ${2, 3, 4, 5, 6}$
- Index 2 occupies ${7, 8, 9}$
For $r = 2$, bisect_right on [2, 7, 10] yields index 1, correctly placing $r=2$ into the second interval.
Python Code
import bisect
import random
from typing import List
class WeightedRandomSampler:
def __init__(self, weights: List[int]):
self.prefix_sums: List[int] = []
current_sum = 0
for w in weights:
current_sum += w
self.prefix_sums.append(current_sum)
self.total_weight = current_sum
def pick_index(self) -> int:
# Generate uniform integer r in [0, self.total_weight - 1]
target = random.randrange(self.total_weight)
# Find first prefix sum strictly greater than target
return bisect.bisect_right(self.prefix_sums, target)
Custom Binary Search Implementation
If asked to avoid standard library functions:
def pick_index_manual(self) -> int:
target = random.randrange(self.total_weight)
low, high = 0, len(self.prefix_sums) - 1
while low < high:
mid = (low + high) // 2
if self.prefix_sums[mid] > target:
high = mid
else:
low = mid + 1
return low
Complexity Analysis
- Preprocessing Time: $\mathcal{O}(N)$ to compute the prefix sums for $N$ elements.
- Preprocessing Space: $\mathcal{O}(N)$ memory to store the
prefix_sumsarray. - Sampling Time: $\mathcal{O}(\log N)$ per call to
pick_indexvia binary search. - Sampling Space: $\mathcal{O}(1)$ additional space per query.
Key Discussion Points & Variations
-
Integer Arithmetic & Overflow Concerns:
- In languages like C++ or Java,
total_weightcan exceed $2^{31} - 1$ if $N = 10^5$ and $w_i = 10^5$ (max sum $= 10^{10}$). Use 64-bit integer types (long/int64_t) for prefix calculations and random bounds.
- In languages like C++ or Java,
-
Handling Floating-Point Weights:
- If inputs are floating-point numbers, floating-point rounding errors can lead to bugs where target values equal or slightly exceed
prefix_sums[-1]. - Ensure target clamping or use precision-preserving techniques like Kahan summation, or scale weights to integers where possible.
- If inputs are floating-point numbers, floating-point rounding errors can lead to bugs where target values equal or slightly exceed
-
Dynamic Weight Updates:
- If weights change frequently during execution, updating a standard prefix sum array costs $\mathcal{O}(N)$ time.
- Using a Fenwick Tree (Binary Indexed Tree) or Segment Tree allows weight updates and sampling in $\mathcal{O}(\log N)$ time.
-
Constant-Time Sampling (Alias Method):
- Walker's Alias Method achieves $\mathcal{O}(N)$ setup time and $\mathcal{O}(1)$ pick time by rebalancing weights into $N$ equal-probability buckets containing at most two outcomes each. Suitable when query count is extremely high relative to dataset size.