Design a Weighted Sampling Generator with Dynamic Updates
Data Structure DesignModel answerLast updated
Implement a class for weighted sampling that supports O(1) sampling for static inputs and logarithmic updates for dynamic environments.
Create a data structure that accepts a list of positive integer weights $W$ of length $N$ and implements a pick() function. Each call to pick() should return index $i$ with probability proportional to $W[i]$, i.e., $P(i) = \frac{W[i]}{\sum_{j=0}^{N-1} W[j]}$.
Your design should address two scenarios:
- Static Case: Preprocessing is done once on $N \le 10^5$ items, followed by up to $10^7$
pick()operations. Optimizepick()execution time. - Dynamic Extension: Support an additional operation
update(index, delta)that modifies the weight atindexby addingdelta(where the new weight remains positive). Bothupdate()andpick()must run in sublinear time $O(\log N)$.
Discuss choices regarding algorithmic strategies (e.g., cumulative sum arrays vs. alias sampling), integer random sampling precision, bit manipulation tricks, and complexity trade-offs.
Hints
Hint 1
For static weights, how can you partition sample spaces into equal-sized buckets to achieve O(1) sampling time?
Hint 2
To handle integer precision issues with random floats, how can integer range draws guarantee exact probability distribution?
Hint 3
For dynamic updates, consider how a Binary Indexed Tree (Fenwick Tree) allows bitwise binary searching over running totals in O(log N) time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Algorithmic Approaches
Depending on whether the weights are static or updated dynamically, different data structures offer distinct performance characteristics:
1. Static Weights: Cumulative Distribution Function (CDF) + Binary Search
- Initialization: Compute a running sum array $C$ where $C[i] = \sum_{j=0}^{i} W[j]$. The final total sum is $S = C[N-1]$. Time complexity: $O(N)$, Space complexity: $O(N)$.
- Pick: Sample an integer uniformly at random $r \in [1, S]$. Use binary search (
bisect_left) to locate the first index $i$ where $C[i] \ge r$. Time complexity: $O(\log N)$. - Execution Cost: For $10^7$ queries on $10^5$ elements, binary search requires roughly $\log_2(10^5) \approx 17$ operations per sample.
2. Static Weights: Alias Method (Vose's Algorithm)
- Initialization: Rescale weights so that the sum is $N$. Each bucket has a capacity of $1.0$ (or total sum $S$ scaled by $N$). Divide indices into "small" (mass $< 1$) and "large" (mass $\ge 1$) groups. Pair each small item with a portion of a large item to form $N$ buckets, each containing at most two index probabilities: its own and an "alias". Time complexity: $O(N)$, Space complexity: $O(N)$.
- Pick: Draw an index $k \in [0, N-1]$ uniformly at random to pick a bucket. Then make a biased coin flip to decide between index $k$ and its alias $A[k]$. Time complexity: $O(1)$.
- Execution Cost: Highly optimal for static batches ($10^7$ calls), requiring only 2 random integer draws and 1 comparison per pick.
3. Dynamic Weights: Binary Indexed Tree (Fenwick Tree)
- When supporting
update(i, delta), rebuilding an alias table or maintaining an explicit CDF array requires $O(N)$ per update. - A Fenwick Tree maintains cumulative frequency totals in an array of size $N$:
update(i, delta)runs in $O(\log N)$ by updating bit-shifted tree nodes.pick()samples $r \in [1, S]$ and finds the smallest index $i$ with cumulative total $\ge r$. Rather than performing binary search over $O(\log N)$ point queries (which would take $O(\log^2 N)$), we descend the Fenwick tree using bit manipulation in $O(\log N)$ time.
Numerical Stability & Edge Cases
- Integer Arithmetic vs. Floating-Point Bias:
- Standard implementations often use
random.random() * total_weight. For large sums ($> 2^{53}$), floating-point precision drops, causing lower-order bits to be lost and under-representing smaller weights. - Using integer range draws ($r \in [1, S]$) avoids floating-point precision issues completely.
- Standard implementations often use
- Zero and Negative Weights:
- The constructor and update methods must ensure individual weights remain non-negative, and that the total mass $S > 0$. Zero-weight entries will naturally have zero probability of selection in both CDF binary search and Fenwick tree descent.
Python Implementations
Static Solution: Alias Sampling ($O(1)$ Pick)
import random
from typing import List
class StaticAliasPicker:
"""
Vose's Alias Method using integer scaling for exact representation.
Preprocessing: O(N)
Pick: O(1)
Space: O(N)
"""
def __init__(self, weights: List[int], seed: int = None):
if not weights or any(w <= 0 for w in weights):
raise ValueError("Weights must be non-empty and positive.")
self.rng = random.Random(seed)
self.n = len(weights)
self.total = sum(weights)
# Scale all weights by N to avoid floating-point loss
# Target weight per bucket is total
scaled = [w * self.n for w in weights]
self.prob = [0] * self.n
self.alias = [0] * self.n
small = []
large = []
for i, val in enumerate(scaled):
if val < self.total:
small.append(i)
else:
large.append(i)
while small and large:
s = small.pop()
l = large.pop()
self.prob[s] = scaled[s]
self.alias[s] = l
# Transfer remaining weight capacity from large to small
scaled[l] = (scaled[l] + scaled[s]) - self.total
if scaled[l] < self.total:
small.append(l)
else:
large.append(l)
while large:
self.prob[large.pop()] = self.total
while small:
self.prob[small.pop()] = self.total
def pick(self) -> int:
bucket = self.rng.randrange(self.n)
# Compare integer draw against threshold
if self.rng.randrange(self.total) < self.prob[bucket]:
return bucket
return self.alias[bucket]
Dynamic Solution: Fenwick Tree Bitwise Descent ($O(\log N)$ Pick & Update)
import random
from typing import List
class DynamicWeightedPicker:
"""
Binary Indexed Tree (Fenwick Tree) with bitwise prefix descent.
Preprocessing: O(N)
Pick: O(log N)
Update: O(log N)
Space: O(N)
"""
def __init__(self, weights: List[int], seed: int = None):
if not weights or any(w <= 0 for w in weights):
raise ValueError("Weights must be non-empty and positive.")
self.rng = random.Random(seed)
self.n = len(weights)
self.weights = list(weights)
self.tree = [0] * (self.n + 1)
# Build Fenwick tree in O(N)
for i in range(1, self.n + 1):
self.tree[i] += self.weights[i - 1]
parent = i + (i & -i)
if parent <= self.n:
self.tree[parent] += self.tree[i]
def update(self, index: int, delta: int) -> None:
if not (0 <= index < self.n):
raise IndexError("Index out of bounds.")
if self.weights[index] + delta <= 0:
raise ValueError("Updated weight must remain strictly positive.")
self.weights[index] += delta
curr = index + 1
while curr <= self.n:
self.tree[curr] += delta
curr += curr & -curr
def pick(self) -> int:
total_sum = self.tree_sum()
target = self.rng.randint(1, total_sum)
# Bitwise tree descent to find smallest index with prefix sum >= target
idx = 0
# Find highest power of 2 <= self.n
mask = 1 << (self.n.bit_length() - 1)
while mask > 0:
next_idx = idx + mask
if next_idx <= self.n and self.tree[next_idx] < target:
idx = next_idx
target -= self.tree[idx]
mask >>= 1
return idx
def tree_sum( करावे) -> int:
curr = self.n
s = 0
while curr > 0:
s += self.tree[curr]
curr -= curr & -curr
return s
Complexity Summary
| Strategy | Preprocessing | pick() | update() | Auxiliary Space |
|---|---|---|---|---|
| Prefix Sum + Binary Search | $O(N)$ | $O(\log N)$ | $O(N)$ | $O(N)$ |
| Alias Method (Vose) | $O(N)$ | $O(1)$ | $O(N)$ (Rebuild) | $O(N)$ |
| Fenwick Tree (Dynamic) | $O(N)$ | $O(\log N)$ | $O(\log N)$ | $O(N)$ |