Skip to contentKEEP THE CRAFTTHE SANCTUARY

Reservoir Sampling

Maintain a uniform sample over stream positions without knowing the final length. Use one fresh uniform draw over all positions seen so far, and distinguish a deterministic transition test from a distribution proof.

1 practice exercise1 interview problem

Recognize it when Items arrive once and retaining the full stream is unnecessary or impossible.

Checking your account…

Reservoir Sampling Code Labs

Keep a Uniform Sample from a Stream

Reservoir sampling selects from a stream of unknown length without storing all items. After processing i items, the reservoir invariant gives each seen item equal inclusion probability.

Replace with Decreasing Probability

For a one-item reservoir, keep the first item, then replace it with item i using probability one over i when counting items from one. An integer draw over all seen positions implements that probability exactly.

Trace Reservoir Decisions

Reference
def reservoir_trace(values,draws):
    if not values:return []
    sample=values[0];trace=[]
    for index,item in enumerate(values[1:],1):
        draw=draws[index-1];replaced=draw==0
        if replaced:sample=item
        trace.append([item,draw,replaced,sample])
    return trace
Practice

Implement reservoir_trace(values,draws). For item index i after the first, draws supplies an integer in [0,i]; return [item,draw,replaced,sample].

Public tests

  • Replace on one of i plus one outcomes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Reservoir Decisions

def reservoir_trace(values,draws):
    if not values:return []
    sample=values[0];trace=[]
    for index,item in enumerate(values[1:],1):
        draw=draws[index-1];replaced=draw==0
        if replaced:sample=item
        trace.append([item,draw,replaced,sample])
    return trace

Keep Then Replace Under Supplied Draws

Predict the existing trace with supplied legal draws. The sample stays p on draw 1, then becomes r on draw 0. Repeating this fixed call is intentionally deterministic and does not measure randomness.

Step Executed statement State Why
Seed first item sample=values[0];trace=[] sample="p", trace=[] The first occurrence is the whole one-item population.
Second item draw draw=draws[index-1];replaced=draw==0;trace.append([item,draw,replaced,sample]) index=1, draw=1, sample="p" One of two legal outcomes preserves the old sample.
Third item draw draw=draws[index-1];replaced=draw==0;sample=item;trace.append([item,draw,replaced,sample]) index=2, draw=0, sample="r" One of three legal outcomes selects the new occurrence.
Empty input if not values:return [] [] No first item exists; the trace has no decision rows.
Print Output
print(reservoir_trace(["p","q","r"],[1,0])) [['q', 1, False, 'p'], ['r', 0, True, 'r']]
print(reservoir_trace([],[])) []

For k slots at seen count t, choose one integer from 0 through t-1 and replace slot draw only if draw < k. The new occurrence enters with k/t, while an old selected occurrence survives with 1-1/t. Combining its earlier inclusion k/(t-1) gives k/t.

Generalize from One Item to K

Fill k reservoir slots, then for seen count i draw uniformly from zero through i minus one. Replace a slot only when the draw is below k, preserving inclusion probability k over i.

Sample One with Deterministic Draws

Reference
def sample_one(values,draws):
    if not values:return None
    sample=values[0]
    for index,item in enumerate(values[1:],1):
        if draws[index-1]==0:sample=item
    return sample
Practice

Implement sample_one(values,draws). Return one reservoir sample using supplied draws for testability, or None for empty input. For every zero-based item index i from 1 onward, supply one integer draw in [0,i], in item order; empty or singleton input needs no draws.

Public tests

  • Expose random decisions as input

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Sample One with Deterministic Draws

def sample_one(values,draws):
    if not values:return None
    sample=values[0]
    for index,item in enumerate(values[1:],1):
        if draws[index-1]==0:sample=item
    return sample

Require an Explicit Random Source

Production code may accept an RNG object; tests should inject deterministic draws. Modulo-reducing arbitrary random integers can introduce bias unless the source range divides evenly.

Explain It in an Interview

Say: “At t items, a new occurrence is selected with probability 1/t. A previously selected occurrence survives with (t-1)/t, reducing its chance from 1/(t-1) to 1/t.” State streaming space separately from these sliced-sequence Labs, and define the empty result.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Reservoir Sampling proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
True iterator one-slot samplingO(n)O(n)One visit and bounded-cost draw per item.
Displayed one-slot LabsO(n)O(n)values[1:] creates an O(n) slice before iteration; the trace also stores O(n) rows.

Space

A streaming implementation needs O(1) sample state, or O(k) for k slots. These sequence Labs use O(n) temporary slicing and trace storage where applicable.

Assumptions

  • Deterministic draws prove state transitions, not empirical randomness or universal RNG quality.
  • For fewer than k items, a generalized reservoir holds all seen items rather than exactly k.

Invariants Worth Saying Aloud

  1. After t seen items, each position has inclusion probability 1/t for one slot.
  2. A k-slot reservoir has k distinct positions and each has inclusion probability k/t once t>=k.
  3. The one-slot transition replaces only when the draw is zero in range 0 through index.

When To Use Or Avoid Reservoir Sampling

Use It When

  • Use a one-slot reservoir for one uniform item or k slots for a uniform subset of positions.
  • Inject legal draw values in tests while supplying uniform independent draws in actual sampling.

Choose Another Tool When

  • For a resident indexed sequence, direct random choice can avoid scanning all items.
  • Weighted sampling requires a different probability rule.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Excluding the newest item from the draw range

At index 3, four items have been seen. range(3) omits one equally eligible outcome and makes replacement probability 1/3 instead of 1/4.

Prevent it: Use randrange(index+1), equivalent to a legal range of 0 through index.

Avoid

eligible=list(range(index))

Use instead

eligible=list(range(index+1))

Replacing on any nonzero draw

For index 2 the legal draws are 0,1,2. Replacing on truthy values chooses two outcomes instead of exactly one.

Prevent it: Test draw == 0 explicitly.

Avoid

replaced=bool(draw)

Use instead

replaced=draw==0

Refusing to sample a falsy value

A selected stream item can be 0. Treating its truthiness as acceptance keeps an older item and biases values.

Prevent it: Let the draw decide replacement, regardless of item truthiness.

Avoid

sample=item if item else sample

Use instead

sample=item

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.