Linear Scans & State · 15 min · free lesson

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.

Core idea

When the supplied uniform choice in 0..=i equals i. 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.

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=118 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=[5,6,7]; choices=[0,0,2]

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(&[5, 6, 7], &[0, 0, 2]).map_or("none".into(), |x| x.to_string());
    println!("{result}");
}

Try your own version

Change the independent fixture `values=[5,6,7]; choices=[0,0,2]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `values=[10,20,30,40]; choices=[0,1,1,3]`.

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 the lesson's own example.

Understand it

When the supplied uniform choice in 0..=i equals i. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input values=[5,6,7]; choices=[0,0,2], the worked program returns 7. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input values=[10,20,30,40]; choices=[0,1,1,3]; predict that result before opening the answer reveal. The precise 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.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: 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. On input values=[10,20,30,40]; choices=[0,1,1,3], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Replace a fixed reservoir with decreasing probability while streaming unknown-length input. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. 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. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(n) time · O(1) reservoir state for k=1; explain which operation dominates it and how many times the input can trigger that operation. Use an empty slice and a one-element slice as checks. Initial values must not silently assume that at least one item exists. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

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(&[5, 6, 7], &[0, 0, 2]).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.

Practice starter

pub fn solve(input: &str) -> String {
    // 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.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement reservoir-sampling")
}

Try it

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.

What success looks like: The private harness prints PASS reservoir-sampling. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for reservoir-sampling: with input values=[8,7,6]; choices=[0,1,0], what result should solve return?

Reveal the answer
  1. 7
  2. 8
  3. 6

For this input the result is 7. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: When the supplied uniform choice in 0..=i equals i. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses values=[5,6,7]; choices=[0,0,2] and computes 7. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For values=[8,7,6]; choices=[0,1,0], the independently calculated result is 7. The complexity discussion uses O(n) time · O(1) reservoir state for k=1. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture values=[5,6,7]; choices=[0,0,2] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge values=[10,20,30,40]; choices=[0,1,1,3].

Connections

  • Reservoir Sampling: When to Use It: uniform sampling from streams and files too large for memory
  • Floyd State Cycle Detection: Mental Model: Advance one state once and another twice; their meeting proves a cycle without a visited set.
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: Challenge: Reservoir Sampling (courseId "algorithms", lessonId "algorithm.reservoir-sampling.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.reservoir-sampling.challenge
Goal: When the supplied uniform choice in 0..=i equals i. 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.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.reservoir-sampling.challenge) 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.