Linear Scans & State · 12 min · free lesson

Reservoir Sampling: When to Use It

Recognise the problem shape before choosing Reservoir Sampling.

Core idea

When the supplied uniform choice in 0..=i equals i. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Replace a fixed reservoir with decreasing probability while streaming unknown-length input.

O(n) time · O(1) reservoir state for k=122 execution steps
main · before line 14Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputvalues=[10,20,30,40]; choices=[0,1,1,3]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 14
fn reservoir(values: &[i32], choices: &[usize]) -> Option<i32> {
    assert_eq!(values.len(), choices.len());
    let mut selected = None;
    for (i, (&value, &choice)) in values.iter().zip(choices).enumerate() {
        assert!(choice <= i); // choice is uniform in 0..=i in a random run
        if choice == i {
            selected = Some(value);
        }
    }
    selected
}
 
fn main() {
    let result =
        reservoir(&[10, 20, 30, 40], &[0, 1, 1, 3]).map_or("none".into(), |x| x.to_string());
    println!("{result}");
}

Try your own version

Compare the visible input `values=[10,20,30,40]; choices=[0,1,1,3]` with `values=[1,2,3,4]; choices=[0,0,0,0]`. Predict why their results are `40` and `1`. Then change one legal value and explain whether the same invariant, when the supplied uniform choice in 0..=i equals i, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Linear Scans & State infographic; panel 4 illustrates Reservoir Sampling.
Reservoir Sampling: follow panel 4 to see the operation, then trace this lesson's example.

Understand it

With choices [0,1,1,3], index 0 selects 10, index 1 selects 20, index 2 retains 20, and index 3 selects 40. Each index i replaces with probability 1/(i+1); the supplied choices make that decision reproducible.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Parse equally sized values and choices arrays. At zero-based index i, choices[i] is in 0..=i; replace the one-item reservoir exactly when choices[i] == i. Return the selected value, or none for empty arrays. The visible fixture is values=[10,20,30,40]; choices=[0,1,1,3] and its example result is 40. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Reservoir Sampling when it asks for uniform sampling from streams and files too large for memory. Here the concrete task is: Parse equally sized values and choices arrays. At zero-based index i, choices[i] is in 0..=i; replace the one-item reservoir exactly when choices[i] == i. Return the selected value, or none for empty arrays. The visible input values=[10,20,30,40]; choices=[0,1,1,3] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Ask whether one pass is enough, whether order matters, and whether a later query will need information you already discarded. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Replace a fixed reservoir with decreasing probability while streaming unknown-length input. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A scan turns a sequence into a small piece of state. Say what the state means after the first i elements, before you describe a loop body. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n) time · O(1) reservoir state for k=1; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 40 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Use an empty slice and a one-element slice as checks. Initial values must not silently assume that at least one item exists. A borrowed slice and a for loop usually express the traversal clearly; distinguish an index you need to return from a value you merely read. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Replace a fixed reservoir with decreasing probability while streaming unknown-length input.

When to use it: uniform sampling from streams and files too large for memory

Complexity: O(n) time · O(1) reservoir state for k=1

Input: values=[10,20,30,40]; choices=[0,1,1,3]

Read the code

fn reservoir(values: &[i32], choices: &[usize]) -> Option<i32> {
    assert_eq!(values.len(), choices.len());
    let mut selected = None;
    for (i, (&value, &choice)) in values.iter().zip(choices).enumerate() {
        assert!(choice <= i); // choice is uniform in 0..=i in a random run
        if choice == i {
            selected = Some(value);
        }
    }
    selected
}

fn main() {
    let result =
        reservoir(&[10, 20, 30, 40], &[0, 1, 1, 3]).map_or("none".into(), |x| x.to_string());
    println!("{result}");
}

Complete std-only reservoir-sampling program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Reservoir Sampling on input values=[9]; choices=[0]. Which result follows from the documented contract?

Reveal the answer
  1. 10
  2. 9
  3. 8

For this input the result is 9. When the supplied uniform choice in 0..=i equals i. Compare this independent fixture with the worked trace: With choices [0,1,1,3], index 0 selects 10, index 1 selects 20, index 2 retains 20, and index 3 selects 40. Each index i replaces with probability 1/(i+1); the supplied choices make that decision reproducible.

Go deeper

Common misconception: “Whenever the new value is larger”

When the supplied uniform choice in 0..=i equals i. With choices [0,1,1,3], index 0 selects 10, index 1 selects 20, index 2 retains 20, and index 3 selects 40. Each index i replaces with probability 1/(i+1); the supplied choices make that decision reproducible.

  1. Concrete transition: With choices [0,1,1,3], index 0 selects 10, index 1 selects 20, index 2 retains 20, and index 3 selects 40. Each index i replaces with probability 1/(i+1); the supplied choices make that decision reproducible.
  2. Independent second fixture: Input values=[9]; choices=[0] produces 9. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input values=[8,7,6]; choices=[0,1,0] produces 7. When the supplied uniform choice in 0..=i equals i. The stated work bound is O(n) time · O(1) reservoir state for k=1. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input values=[10,20,30,40]; choices=[0,1,1,3] with values=[1,2,3,4]; choices=[0,0,0,0]. Predict why their results are 40 and 1. Then change one legal value and explain whether the same invariant, when the supplied uniform choice in 0..=i equals i, still applies.

Connections

  • Reservoir Sampling: Mental Model: Replace a fixed reservoir with decreasing probability while streaming unknown-length input.
  • Challenge: Reservoir Sampling: Parse equally sized values and choices arrays. At zero-based index i, choices[i] is in 0..=i; replace the one-item reservoir exactly when choices[i] == i. Return the selected value, or none for empty arrays.
Reveal the Algorithm Atlas answer

40

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Reservoir Sampling: When to Use It (courseId "algorithms", lessonId "algorithm.reservoir-sampling.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.reservoir-sampling.recognize
Goal: When the supplied uniform choice in 0..=i equals i. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.reservoir-sampling.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.