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)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 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.
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.
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 traceImplement reservoir_trace(values,draws). For item index i after the first, draws supplies an integer in [0,i]; return [item,draw,replaced,sample].
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 tracePredict 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. |
| 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.
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.
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 sampleImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 sampleProduction 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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| True iterator one-slot sampling | O(n) | O(n) | One visit and bounded-cost draw per item. |
| Displayed one-slot Labs | O(n) | O(n) | values[1:] creates an O(n) slice before iteration; the trace also stores O(n) rows. |
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.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
eligible=list(range(index))eligible=list(range(index+1))Where you will hit this: Simulate Reservoir Sampling(opens in a new tab)
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.
replaced=bool(draw)replaced=draw==0Where you will hit this: Simulate Reservoir Sampling(opens in a new tab)
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.
sample=item if item else samplesample=itemWhere you will hit this: Shortest Subarray With OR at Least K(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27