---
title: Reservoir sampling (deterministic RNG contract)
url: https://gurkanozkan.ai/learn/coding/mle-reservoir-sampling-deterministic-rng-contract-27/
markdown: https://gurkanozkan.ai/learn/coding/mle-reservoir-sampling-deterministic-rng-contract-27.md
kind: coding
difficulty: Easy
topics:
  - Sampling
  - Streaming
json: https://gurkanozkan.ai/api/learn/coding/mle-reservoir-sampling-deterministic-rng-contract-27.json
robots: noindex
---

# Reservoir sampling (deterministic RNG contract)

Using `rng = random.Random(seed)`: - Copy the first `k` items into the reservoir in order. - For each later item at 0-based index `i ≥ k`, call `j = rng.randint(0, i)` (inclusive) exactly once; if `j < k`, replace `reservoir[j]`. - Return the reservoir. If the stream has fewer than `k` items, return all of them.

## Signature

```python
def reservoir_sample(stream, k: int, seed: int) -> list: ...
```

## Examples

Each call and the value it should give.

```python
>>> reservoir_sample([1, 2], 5, seed=0) == [1, 2]
True

>>> reservoir_sample(range(3), 3, seed=42) == [0, 1, 2]
True
```

## Hints

1. Copy the first k items; for each later item, draw j = rng.randint(0, i) exactly once.
2. If j < k, replace reservoir[j]; keep the exact RNG contract (seed and call sequence).
3. Each item survives with probability k/n — no whole stream stored.

## Reference solution

```python
import random

def reservoir_sample(stream, k, seed):
    rng = random.Random(seed)
    res = []
    for i, item in enumerate(stream):
        if i < k:
            res.append(item)
        else:
            j = rng.randint(0, i)
            if j < k:
                res[j] = item
    return res
```

## What a strong solution covers

- Proves each item survives with probability k/n (induction).
- Single pass with O(k) memory.
- Follow-ups: weighted reservoir (A-Res, keys u^(1/w)) and stratified sampling to match a target distribution.

## Common mistakes

- `randint(0, i − 1)` or `randint(1, i)` off-by-one (biased)
- storing the whole stream.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
