Streaming Weighted Reservoir Sampling Without Replacement
Heaps, Sorting & SearchModel answerLast updated
Implement a single-pass, memory-efficient weighted sampler that draws k distinct items proportional to weight from a potentially huge stream.
Streaming Weighted Reservoir Sampling
You are building a data pipeline that processes a very large stream of items — too large to hold in memory — where each item carries a positive numeric weight. Your task is to draw a fair random sample from it.
Your function
def sample_k(items, weights, k, seed=None):
...
items— an iterable of any objects (can be a generator; do not assume a list)weights— a parallel iterable of positive floatsk— number of items to returnseed— optional integer for reproducibility; must not affect global RNG state
Returns a list of exactly min(k, N) distinct items drawn without replacement, where item i is selected according to successive-sampling (Plackett–Luce) semantics: at each draw step, the probability of picking item i from the remaining pool is proportional to its weight.
Hard requirements
| Requirement | Detail |
|---|---|
| Single pass | Read each item exactly once; do not buffer the stream |
| O(k) memory | Only the current sample and a fixed amount of working state |
| Extreme weights | Must handle weights anywhere in roughly [5e-324, 1e300] without overflow, underflow, or artificial ties |
| Reproducible | Same seed + same stream → identical output, every time |
| Graceful rejection | Non-positive, infinite, or non-numeric weights must raise ValueError with the offending index and value |
What to produce
- A working Python implementation that satisfies all five requirements above.
- A clear explanation of the algorithm you chose, why it is correct (a proof sketch is fine), and how you handle numerical stability.
- A description of the tests you would write to give you confidence the implementation is actually unbiased.
Constraints
Nup to1e8kis a non-negative integer;k > Nis valid (return all N items)- Weights are floats;
NaN,0, negative values, andinfare all invalid
Examples
# Deterministic with seed
sample_k(["a","b","c","d"], [1, 2, 3, 4], k=2, seed=42)
# → e.g. ["d", "c"] (exact output depends on RNG; must be stable across runs)
# k larger than population
sample_k(["x","y"], [1.0, 1.0], k=5, seed=0)
# → ["x", "y"] (all items, order reflects draw order)
# Bad weight
sample_k(["a","b"], [1.0, -3.0], k=1)
# → ValueError: weight at index 1 is non-positive or invalid: -3.0
Hints
Hint 1
Think about assigning each item an independent random 'priority score' derived from its weight, then keeping track of only the top-k scores seen so far. What probability distribution makes this equivalent to drawing proportional to weight?
Hint 2
A max-heap of size k is the right data structure: once it is full, you only update it when the new item's score beats the worst score currently in the heap. What is the heap's invariant, and how does that guarantee you end up with the k best scores after one pass?
Hint 3
The naive score u^(1/w) collapses to 1.0 when w is huge (like 1e300), causing all heavy items to tie. Take the log of the score instead and work entirely in log space — addition replaces multiplication, and the ordering is preserved because log is strictly monotone.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Exponential Race Keys in Log Space
The right mental model
Successive sampling (Plackett–Luce) is the semantics here. You draw one item with probability w_i / W, remove it, renormalize, and repeat. This is not the same as guaranteeing each item's final inclusion probability is proportional to its weight — for heavy items, inclusion probabilities saturate near 1. Naming this distinction in an interview signals you understand the actual distribution you are guaranteeing.
Algorithm: Efraimidis–Spirakis A-Res
Assign each item i an independent "arrival key":
key_i = Exp(1) / w_i
where Exp(1) is a standard exponential random variable. Keep the k items with the smallest keys. That is the entire algorithm.
Why it works. The minimum of independent Exp(w_i) variables has probability w_j / W of belonging to item j (a standard competing-exponentials result). By the memorylessness of the exponential distribution, conditioning on which item won and discarding it leaves the remaining overshoots as independent Exp(w_i) variables — identical in distribution to a fresh start without item j. Applying this recursively proves that the k smallest keys follow exactly the Plackett–Luce distribution. The heap retains the k smallest keys seen so far, and since "smallest k of N" is order-independent, streaming correctness follows.
The practical key is u^(1/w) (keep k largest), which is equivalent because -log(u^(1/w)) = -log(u)/w = Exp(1)/w.
Numerical stability: always work in log space
With w = 1e300, u^(1/w) rounds to exactly 1.0 for every u — every heavy item ties, and the sampler is completely broken. The fix is:
log_key_i = log(Exp(1)) - log(w_i)
= log(-log(u_i)) - log(w_i)
log(w) is finite for all positive finite doubles (range roughly −744 to +709). log(-log(u)) for u ∈ (0,1) stays in about [−37, +7]. All keys therefore live in ±750; there is no overflow, no underflow, and no ties. The ordering is preserved because log is strictly monotone.
Streaming with a max-heap
Once the reservoir has k items, a new item only enters if its key is smaller than the current worst. A max-heap (inverted with negation in Python) gives O(log k) updates and O(1) threshold lookups.
Complexity
- Time: O(N log k) worst case; in practice closer to O(N + k log k · log(N/k)) because the heap is updated infrequently once the threshold drops.
- Space: O(k).
For N = 1e8 in pure Python, the dominant cost is the Python loop. A practical speedup is to vectorize key computation over chunks using NumPy and filter against the current threshold with argpartition before touching the heap.
Implementation
import heapq
import math
import random
from typing import Any, Iterable, List, Optional
def sample_k(
items: Iterable[Any],
weights: Iterable[float],
k: int,
seed: Optional[int] = None,
) -> List[Any]:
"""Weighted sampling without replacement via log-space exponential keys.
Successive-sampling (Plackett-Luce) semantics. Single pass, O(k) memory.
"""
if not isinstance(k, int) or k < 0:
raise ValueError(f"k must be a non-negative integer, got {k!r}")
if k == 0:
return []
rng = random.Random(seed) # private instance: no global state mutation
heap: List[tuple] = [] # max-heap stored as (-log_key, insertion_idx, item)
for idx, (item, w) in enumerate(zip(items, weights, strict=True)):
try:
w = float(w)
except (TypeError, ValueError):
raise ValueError(
f"weight at index {idx} is not numeric: {w!r}"
)
if not (w > 0.0) or math.isinf(w):
raise ValueError(
f"weight at index {idx} is non-positive or invalid: {w!r}"
)
# Draw u in (0, 1); redraw the ~2^-53 chance of exactly 0.0
u = rng.random()
while u == 0.0:
u = rng.random()
# log-space key: smaller is higher priority
log_key = math.log(-math.log(u)) - math.log(w)
entry = (-log_key, idx, item) # negate so heapq acts as max-heap
if len(heap) < k:
heapq.heappush(heap, entry)
elif log_key < -heap[0][0]: # beats current worst
heapq.heapreplace(heap, entry)
# Sort ascending by log_key to return items in draw order (first draw first)
heap.sort(key=lambda t: -t[0])
return [item for _, _, item in heap]
Key details: zip(..., strict=True) raises on length mismatch. The insertion index idx breaks key ties (probability ≈ 0 in practice) so items are never compared directly. The private random.Random(seed) instance makes output a deterministic function of (seed, stream) without touching the module-level RNG.
Tests worth writing
Goodness-of-fit. Use 4 items with weights [1, 2, 3, 4] and k=2. Enumerate all 12 ordered pairs, compute their exact Plackett–Luce probabilities, run ~200k seeded trials, and apply a chi-square test. Also verify marginal first-draw frequencies match w_i / W.
Extreme weights. With [1e300, 1e-300, 1.0] and k=1, the 1e300 item should win nearly every trial. With all weights equal to 1e300, first-draw frequencies should be uniform — no ties or collapse. The ratio of draw frequencies for [1e300, 2e300] should be approximately 1:2.
Scale invariance. Multiplying all weights by 1e200 or 1e-200 should not change the chi-square fit against the original distribution.
Seed determinism. Same seed → identical output on repeated calls. Different seeds → different outputs. Generators produce the same result as equivalent lists.
Edge cases. Cover k=0, k=N, k>N (returns all N), empty stream, N=1, and length mismatch. Bad weights (0, -1, inf, NaN, "hello") should all raise ValueError with the correct index.
Common mistakes
- Using
u^(1/w)directly — breaks entirely for extreme weights. - Touching
random.seed()globally — breaks other code in the same process. - Not handling
u = 0.0—log(0)raises. - Claiming inclusion probabilities are exactly proportional to weight — they are not; successive-sampling semantics is the correct claim.
- Sorting the final heap by key and presenting that as "draw order" — make sure the sort direction matches the semantics (smallest key = first draw).