Sampling
🎰 What is weighted sampling? Weighted sampling picks item
iwith probability proportional to its weightw_i. With replacement, the weights never change, and one prefix-sum array plus a binary search does every draw. Without replacement, every draw changes a weight, and the question becomes which data structure keeps the draw fast.
Nuro asked a machine learning engineer, in a phone screen run by a research scientist, to draw balls of k
colours without replacement in O(log k) per draw, where prefix sums and binary search alone only give sampling
with replacement (the question).
Anthropic asked a research engineer, in the onsite, to build a weighted data batcher over a data registry with a
sampling API, then make it checkpoint and resume from an offset, then handle a batch size not divisible by the sum
of the weights (the question).
The Prompt
The interviewer starts from the version everyone knows and removes the assumption that makes it easy.
"You have
kcolours of balls with counts[n_1, ..., n_k]. Write a sampler that draws one ball at a time, without replacement, inO(log k)per draw."
Clarifying Questions
You: How large are the counts? If the total is in the billions, I can't expand the balls into a list.
Interviewer: Assume up to 10^9 per colour and k up to 10^5.
You: What does a draw return, and what happens when the bag is empty?
Interviewer: The colour index. Raise when it's empty.
You: Can I pass in a random generator, and expose a way to feed a fixed number for testing?
Interviewer: Yes.
You: Should I also support drawing with replacement?
Interviewer: Start there, it's a one-liner, then do the real problem.
What You'll Build
sample_with_replacement(w, m, rng) -> (m,): inverse-CDF sampling with a prefix sum andsearchsorted.BallSampler(counts, rng)withdraw() -> intinO(log k)and the bag shrinking by one each draw.sample_without_replacement(w, m, rng) -> (m,):mdistinct items, weighted, in one vectorized pass.reservoir_sample(stream, m, rng) -> list: a uniform sample of a stream of unknown length.WeightedBatcher(sources, weights, batch_size): batches mixed by weight, withstate_dictandload_state_dict.