KatInterview

Streaming Weighted Reservoir Sampling Without Replacement

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchreservoir-samplingprobabilitynumerical-stability

Last 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 floats
  • k — number of items to return
  • seed — 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

RequirementDetail
Single passRead each item exactly once; do not buffer the stream
O(k) memoryOnly the current sample and a fixed amount of working state
Extreme weightsMust handle weights anywhere in roughly [5e-324, 1e300] without overflow, underflow, or artificial ties
ReproducibleSame seed + same stream → identical output, every time
Graceful rejectionNon-positive, infinite, or non-numeric weights must raise ValueError with the offending index and value

What to produce

  1. A working Python implementation that satisfies all five requirements above.
  2. A clear explanation of the algorithm you chose, why it is correct (a proof sketch is fine), and how you handle numerical stability.
  3. A description of the tests you would write to give you confidence the implementation is actually unbiased.

Constraints

  • N up to 1e8
  • k is a non-negative integer; k > N is valid (return all N items)
  • Weights are floats; NaN, 0, negative values, and inf are 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.