Alias Method Categorical Sampler
Data Structure DesignAuto-graded · 23 test casesLast updated
Generate discrete random samples according to custom category weights in constant time per sample using Vose's alias algorithm.
You are tasked with implementing a fast categorical distribution sampler based on Vose's Alias Method. Given a list of non-negative relative category weights and a sequence of uniform random floating-point numbers in the range $[0, 1)$, generate the corresponding drawn outcome indices.
The alias method constructs an $O(k)$ lookup structure (where $k$ is the number of categories) containing two length-$k$ arrays: threshold (floating-point cutoffs in $[0, 1]$) and alias (fallback indices). Each sample is drawn using a single uniform random value $u \in [0, 1)$:
- Calculate a continuous scaled position $x = u \times k$.
- Determine the column index $i = \min(\lfloor x \rfloor, k - 1)$.
- Compute the fractional residual $f = x - i$.
- If $f < \text{threshold}[i]$, choose outcome $i$. Otherwise, choose outcome $\text{alias}[i]$.
Construction Algorithm Details
- If the input list of weights is empty, return an empty list of samples.
- If the total sum of weights is less than or equal to $0$, raise a
ValueError. - Normalize and scale the input weights so their average is $1.0$: $\text{scaled}[i] = \frac{\text{weight}[i] \times k}{\sum \text{weights}}$.
- Separate category indices into two work lists:
small(indices where $\text{scaled}[i] < 1.0$) andlarge(indices where $\text{scaled}[i] \ge 1.0$). - While both
smallandlargeare non-empty:- Pop an index $s$ from
smalland an index $l$ fromlarge. - Set $\text{threshold}[s] = \max(0.0, \min(1.0, \text{scaled}[s]))$.
- Set $\text{alias}[s] = l$.
- Subtract $(1.0 - \text{threshold}[s])$ from $\text{scaled}[l]$.
- If the new $\text{scaled}[l] < 1.0$, push $l$ into
small; otherwise, push $l$ intolarge.
- Pop an index $s$ from
- For any remaining indices left in either
smallorlarge(due to floating-point rounding), set $\text{threshold}[i] = 1.0$ and $\text{alias}[i] = i$.
Sampling Rules
For each value $u$ in uniforms:
- If $u < 0.0$ or $u \ge 1.0$, raise a
ValueError. - Map $u$ to a sampled category index using the alias table lookup described above.
Constraints
- $0 \le k \le 10^5$, where $k$ is the length of
weights. - $0 \le m \le 10^5$, where $m$ is the length of
uniforms. - Each element in
weightsis a non-negative float ($0.0 \le \text{weights}[i] \le 10^9$). - Each element in
uniformsis a float.
Standard Inputs & Outputs
- Input:
weights: List[float],uniforms: List[float] - Output:
List[int](the sampled category indices)
Examples
Example 1
Input: alias_method_samples([0.5, 0.3, 0.2], [0, 0.19, 0.2, 0.49, 0.5, 0.79, 0.8, 0.99])
Output: [0, 0, 0, 1, 1, 2, 2, 0]
Example 2
Input: alias_method_samples([1], [0, 0.2, 0.999999])
Output: [0, 0, 0]
Example 3
Input: alias_method_samples([0.25, 0.25, 0.25, 0.25], [0, 0.249999, 0.25, 0.5, 0.749999, 0.75, 0.999999])
Output: [0, 0, 1, 2, 2, 3, 3]
Example 4
Input: alias_method_samples([0.7, 0, 0.3], [0, 0.2, 0.69, 0.7, 0.99])
Output: [0, 0, 2, 2, 0]
Hints
Hint 1
Construct two work lists, one for indices with scaled weight < 1.0 and one for indices with scaled weight >= 1.0.
Hint 2
In each step of the table build, pair a underfull index with an overfull index to finalize a column in O(1) time.
Hint 3
Use the integer part of (u * k) to select the column and the fractional residual as the comparison threshold.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The Alias Method (specifically Vose's variant) allows constant-time $O(1)$ sampling from any discrete probability distribution over $k$ outcomes after an initial $O(k)$ pre-computation phase.
1. Table Construction ($O(k)$)
- Scale weights by $\frac{k}{\sum \text{weights}}$, making the average scaled weight equal to $1.0$.
- Categorize categories into
small(scaled weight $< 1$) andlarge(scaled weight $\ge 1$). - Repeatedly pop a
smallindex $s$ and alargeindex $l$. Assign column $s$ a cutoff threshold $\text{threshold}[s] = \text{scaled}[s]$ and set its backup outcome $\text{alias}[s] = l$. - Deduct the missing mass $(1.0 - \text{threshold}[s])$ from $l$'s remaining mass. Depending on whether $l$'s new weight is $< 1$ or $\ge 1$, push $l$ into
smallorlarge. - Once processing finishes, set any leftover items' threshold to $1.0$ and alias to themselves.
2. Sampling ($O(1)$ per draw)
Given a single uniform scalar $u \in [0, 1)$:
- Map $u$ into continuous index space: $x = u \times k$.
- The column index is $i = \lfloor x \rfloor$ (clamped to $k-1$ for floating point boundary protection).
- The residual fraction $f = x - i$ acts as the coin flip. If $f < \text{threshold}[i]$, output $i$; otherwise output $\text{alias}[i]$.
Complexity Analysis
- Time Complexity:
- Construction: $O(k)$ because every step of the
whileloop permanently fills one column. - Sampling: $O(1)$ per uniform random value, resulting in $O(m)$ total time for $m$ samples.
- Total Time: $O(k + m)$.
- Construction: $O(k)$ because every step of the
- Space Complexity: $O(k)$ extra space to store
threshold,alias,scaled, and thesmall/largework stacks.
Python Reference Solution
from typing import List
def alias_method_samples(weights: List[float], uniforms: List[float]) -> List[int]:
n = len(weights)
if n == 0:
return []
total = sum(weights)
if total <= 0.0:
raise ValueError("probabilities must have a positive sum")
scaled = [p * n / total for p in weights]
small = [i for i, value in enumerate(scaled) if value < 1.0]
large = [i for i, value in enumerate(scaled) if value >= 1.0]
threshold = [0.0] * n
alias = list(range(n))
while small and large:
s = small.pop()
l = large.pop()
threshold[s] = max(0.0, min(1.0, scaled[s]))
alias[s] = l
scaled[l] -= 1.0 - threshold[s]
if scaled[l] < 1.0:
small.append(l)
else:
large.append(l)
for i in small:
threshold[i] = 1.0
alias[i] = i
for i in large:
threshold[i] = 1.0
alias[i] = i
result = []
for u in uniforms:
if not 0.0 <= u < 1.0:
raise ValueError("uniform values must be in [0, 1)")
position = u * n
column = min(int(position), n - 1)
fraction = position - column
result.append(column if fraction < threshold[column] else alias[column])
return result