Weighted Distribution Sampling from Uniform Draws
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Validate probability weights and map pre-generated uniform float values to discrete outcomes using prefix sums and binary search.
Given a list of unique integer items, a list of non-negative numeric weights corresponding to each item, and a sequence of standard uniform numbers $u \in [0, 1]$, sample an item for each standard uniform number according to the normalized cumulative distribution of the weights.
Requirements & Validation
Before generating any samples, validate all inputs. If any of the following checks fail, raise a ValueError:
valuesandweightsmust have identical, non-zero lengths.valuesmust contain only distinct integers (no duplicate elements).- Every weight in
weightsmust be a finite, non-negative number ($w_i \ge 0$). - The sum of all elements in
weights, $S = \sum w_i$, must be positive, finite, and within $10^{-9}$ of $1.0$ (that is, $|S - 1.0| \le 10^{-9}$). - Every uniform draw $u \in \text{uniforms}$ must be finite and lie within $[0, 1]$.
Precise Mapping Algorithm
To guarantee exact output matching across floating-point implementations, construct the cumulative prefix array as follows:
- Calculate
scale = 1.0 / sum(weights). - Construct a cumulative array
prefixof length $N = \text{len}(values)$ where:- For $i = 0$ to $N-1$, maintain a running float accumulator
running. Updaterunning += weights[i] * scaleand setprefix[i] = running. - Explicitly overwrite
prefix[N - 1] = 1.0.
- For $i = 0$ to $N-1$, maintain a running float accumulator
- For each value $u \in \text{uniforms}$, find the zero-based outcome index using Python's right binary search algorithm (
bisect_right(prefix, u)). - If
index == N(which can happen if $u > 1.0$ due to rounding, or $u == 1.0$), clampindexto $N - 1$. - Return the list of mapped values
values[index].
Constraints
- $1 \le \text{len}(values) \le 10^5$
- $\text{len}(values) == \text{len}(weights)$
- $0 \le \text{len}(uniforms) \le 10^5$
- $0.0 \le w_i \le 1.0$
- $0.0 \le u \le 1.0$
Examples
Example 1
Input: weighted_samples([10, 20, 30], [0.2, 0.3, 0.5], [0, 0.19, 0.2, 0.49, 0.5, 0.99])
Output: [10, 10, 20, 20, 30, 30]
Example 2
Input: weighted_samples([1, 2, 3], [0.5, 0, 0.5], [0.1, 0.5, 0.5000001, 0.999999])
Output: [1, 3, 3, 3]
Example 3
Input: weighted_samples([7, 11], [0.3333333333, 0.6666666667], [0, 0.3333333333, 0.3333333334, 1])
Output: [7, 11, 11, 11]
Hints
Hint 1
Check all input validation constraints first: non-empty matching lengths, unique values, non-negative finite weights, float sum within 1e-9 of 1.0, and uniforms in [0, 1].
Hint 2
Build normalized prefix sums by accumulating weights multiplied by (1.0 / sum(weights)), and set the final entry prefix[-1] explicitly to 1.0.
Hint 3
Use `bisect_right(prefix, u)` to map each uniform float `u` to its target index, clamping the resulting index to len(values) - 1 if it reaches len(values).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires taking standard uniform random samples $u \in [0, 1]$ and mapping them to discrete outcomes based on a discrete probability distribution defined by weights over values.
1. Input Validation
Before constructing cumulative probabilities, all inputs must be strictly validated:
valuesandweightsmust be non-empty lists of identical length.valuesmust contain unique elements (len(set(values)) == len(values)).- Each $w_i \in \text{weights}$ must be non-negative ($w_i \ge 0$) and finite (
math.isfinite(w)). - The sum of weights $S = \sum w_i$ must be finite, positive, and satisfy $|S - 1.0| \le 10^{-9}$.
- Every uniform sample $u \in \text{uniforms}$ must satisfy $0 \le u \le 1$ and be finite.
If any check fails, raise a ValueError.
2. Inverse CDF via Prefix Sums
To convert uniform standard numbers $u \in [0, 1]$ to outcomes:
- Normalize weights by multiplying each by
scale = 1.0 / sum(weights). - Compute cumulative prefix sums
prefix[i]representing the right bound of interval $i$. - Assign
prefix[-1] = 1.0to eliminate potential floating-point representation undershoot at the end of the distribution. - For each draw $u$, search for its target index using standard binary search (
bisect_right). bisect_rightreturns the first index $i$ whereprefix[i] > u.- If $u = 0.0$,
bisect_rightlands on index $0$ (or the first index with non-zero interval), correctly choosingvalues[0]. - If $u$ equals or slightly exceeds
prefix[-1],bisect_rightreturns $N = \text{len}(values)$. In this scenario, clamp the index to $N - 1$.
- If $u = 0.0$,
Complexity Analysis
-
Time Complexity:
- Validation & Prefix Construction: $\mathcal{O}(N)$ where $N = \text{len}(values)$.
- Sampling: $\mathcal{O}(M \log N)$ where $M = \text{len}(uniforms)$, performing a binary search for each uniform draw.
- Overall Time Complexity: $\mathcal{O}(N + M \log N)$.
-
Space Complexity: $\mathcal{O}(N)$ auxiliary space for storing the cumulative prefix sum array, plus $\mathcal{O}(M)$ space for the output array.
from bisect import bisect_right
import math
from typing import List
def weighted_samples(values: List[int], weights: List[float], uniforms: List[float]) -> List[int]:
if len(values) != len(weights) or not values:
raise ValueError("values and weights must have the same nonzero length")
if len(set(values)) != len(values):
raise ValueError("values must be distinct")
if any(not math.isfinite(w) or w < 0 for w in weights):
raise ValueError("weights must be finite and nonnegative")
total = sum(weights)
if not math.isfinite(total) or total <= 0 or abs(total - 1.0) > 1e-9:
raise ValueError("weights must sum to 1 within tolerance")
for u in uniforms:
if not math.isfinite(u) or u < 0 or u > 1:
raise ValueError("uniforms must be in [0, 1]")
scale = 1.0 / total
prefix = []
running = 0.0
for weight in weights:
running += weight * scale
prefix.append(running)
prefix[-1] = 1.0
result = []
for u in uniforms:
index = bisect_right(prefix, u)
if index == len(values):
index -= 1
result.append(values[index])
return result