Sub topic 6
Proving Every Item Has Probability k/n
This chapter assumes you have read the Algorithm R chapter and can follow a proof by induction. It also uses conditional probability and the binomial coefficient C(n, k), the number of ways to choose k items from n. The goal is to show that Algorithm R really produces a uniform sample. We prove it in two strengths. The weaker claim is that every item ends up in the reservoir with probability k/n. The stronger claim is that every possible set of k items is equally likely to be the final reservoir.
The Algorithm We Are Proving
Here is Algorithm R as written earlier in the tutorial. The indices are 0-based, so the item at index i is the (i+1)-th item of the stream.
import random
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # inclusive: 0..i
if j < k:
reservoir[j] = item
return reservoirThe proof is easier to read with 1-based counting, so from here on "item t" means the t-th item to arrive. When item t arrives (t > k), the code draws j uniformly from t values. Two facts follow from that single draw:
- Item t is admitted with probability k/t, because exactly k of the t values satisfy
j < k. - Given that it is admitted, the slot it overwrites is uniform over the k slots, because
jconditioned onj < kis uniform on 0..k−1.
Everything in the proof rests on these two facts.
The Invariant
An invariant is a statement that stays true after every step of a loop. The invariant for Algorithm R is:
After the first t items have been processed (t ≥ k), each of those t items is in the reservoir with probability k/t.
If this holds for every t, then at the end of the stream (t = n) each item has probability k/n. Because the invariant holds at every t, the stream's length never has to be known in advance. The sample is correct whenever you stop reading.
Base case: t = k
The first k items are all copied into the reservoir. Each one is present with probability 1, and k/k = 1. The base case holds.
Inductive step: from t to t + 1
Assume the invariant holds after t items. Item t+1 now arrives. There are two kinds of item to check.
The new item. Item t+1 is admitted with probability k/(t+1), which is exactly the target.
An old item x. By the inductive hypothesis, x is in the reservoir with probability k/t. It stays there unless the new item is admitted and happens to land in x's slot. The two ways x survives are:
| Event when item t+1 arrives | Probability | x survives? |
|---|---|---|
| New item rejected | 1 − k/(t+1) | Yes |
| New item admitted, overwrites another slot | (k/(t+1)) · ((k−1)/k) | Yes |
| New item admitted, overwrites x's slot | (k/(t+1)) · (1/k) | No |
The eviction probability is the last row: (k/(t+1)) · (1/k) = 1/(t+1). So x survives with probability 1 − 1/(t+1) = t/(t+1).
The random draw at step t+1 is independent of everything that came before. So we can multiply:
P(x in reservoir after t+1) = (k/t) · (t/(t+1)) = k/(t+1).
Both kinds of item now have probability k/(t+1), so the invariant holds for t+1. By induction it holds for every t ≥ k, and in particular for t = n.
A Direct Proof Without Induction
The same result follows from a telescoping product, which some readers find more concrete. Take item i with i > k. It must be admitted when it arrives, with probability k/i. Then it must survive every later arrival j = i+1, ..., n. Each survival has probability (j−1)/j, and these events are independent:
P(item i in final reservoir) = (k/i) · ((i)/(i+1)) · ((i+1)/(i+2)) · ... · ((n−1)/n) = (k/i) · (i/n) = k/n.
For an item i ≤ k, the admission factor is 1 and the survival product runs from j = k+1 to n, giving k/n again. The induction proof and this one rest on the same fact. The induction version has one advantage: it states a property that holds at every prefix of the stream.
Edge Cases
- n < k. The stream ends before the reservoir fills. Every item is kept with probability 1, and the reservoir has n items. The correct general statement is that each item has probability min(1, k/n).
- n = 0. The function returns an empty list. There is nothing to prove.
- k = 1. The invariant becomes "each of the first t items is the chosen one with probability 1/t". This is the warm-up algorithm from earlier in the tutorial.
- k = n. No random numbers are drawn, and the sample is the whole stream.
Why Equal Marginals Are Not Enough
The probability that a single item is included is called its marginal inclusion probability. Equal marginals do not guarantee a uniform sample without replacement. Here is a sampler that fails. Split items 0..5 into the blocks {0,1,2} and {3,4,5}, and return one block with probability 1/2 each. Every item has inclusion probability 1/2 = 3/6, but only 2 of the C(6,3) = 20 possible subsets can ever appear. Items 0 and 3 are never sampled together.
A uniform sample of size k means every k-subset of the n items is equally likely, each with probability 1/C(n, k). Algorithm R meets this stronger standard too.
Proving the strong claim
The new invariant is: after t items, the reservoir (viewed as a set) is each k-subset of the first t items with probability 1/C(t, k). The base case t = k is immediate, since there is only one subset. For the inductive step, fix a target k-subset S of the first t+1 items. We use the identity C(t+1, k) = C(t, k) · (t+1)/(t+1−k).
Case 1: S does not contain item t+1. The reservoir must already equal S after t items, which has probability 1/C(t, k). Then the new item must be rejected, with probability (t+1−k)/(t+1). The product is (t+1−k)/((t+1) · C(t, k)) = 1/C(t+1, k).
Case 2: S contains item t+1. Write S = S′ ∪ {t+1}, where S′ has k−1 old items. After t items, the reservoir must have been S′ plus one extra old item y that is not in S′. There are t − (k−1) choices of y, and each such reservoir has probability 1/C(t, k). The new item must then be admitted and must overwrite y specifically: (k/(t+1)) · (1/k) = 1/(t+1). The total is (t−k+1)/((t+1) · C(t, k)) = 1/C(t+1, k).
Both cases give 1/C(t+1, k), so the strong invariant holds for every t. The k/n marginal follows from it, because each item appears in a fraction k/n of all k-subsets.
Checking the Proof Exactly on Small Inputs
A Monte Carlo test, covered in the next chapter, gives approximate frequencies. For small n you can do better. You can enumerate every possible sequence of random draws. Each sequence is equally likely, because the draw at index i is uniform over i+1 values. So the subset distribution is uniform exactly when every subset is produced by the same number of sequences.
from collections import Counter
from itertools import product
from math import comb
def run_with_choices(n, k, choices):
# Replay Algorithm R on items 0..n-1 using a fixed sequence of draws
reservoir = list(range(k))
for i, j in zip(range(k, n), choices):
if j < k:
reservoir[j] = i
return frozenset(reservoir)
def exact_distribution(n, k):
counts = Counter()
draw_ranges = [range(i + 1) for i in range(k, n)] # j in 0..i
for choices in product(*draw_ranges):
counts[run_with_choices(n, k, choices)] += 1
return counts
n, k = 6, 3
counts = exact_distribution(n, k)
print(len(counts), comb(n, k)) # 20 20: every subset is reachable
print(set(counts.values())) # {6}: every subset is reached equally often
print(sum(counts.values())) # 120 = 4 * 5 * 6 draw sequencesThis check is exact. It does not involve sampling error, so a single mismatched count proves a bug. It is a good regression test for variants of the algorithm. Keep n small, because the number of sequences is n!/k!.
Where the Proof Breaks in Practice
The proof assumes two things that code can violate:
- The draw is uniform over exactly t values. An off-by-one range or a biased reduction such as
random_bits % tchanges the admission probability away from k/t. The Common Bugs chapter covers these. - Draws are independent of the data and of each other. The proof multiplies probabilities across steps. If the random choice depends on the item's value, or a poorly seeded generator repeats across runs, that multiplication is no longer valid.
Exercise
Use the telescoping argument to show directly that with k = 1, item i (1-based) is the final choice with probability 1/n.
Show answer
Item i is chosen on arrival with probability 1/i. It survives arrival j with probability (j−1)/j for j = i+1..n. The product is (1/i) · (i/(i+1)) · ... · ((n−1)/n) = (1/i) · (i/n) = 1/n.
Exercise
Suppose the line is changed to j = rng.randint(0, i - 1), so j ranges over i values instead of i+1 (0-based index i). What is the admission probability of the item at index i = k, and which step of the proof fails?
Show answer
At index i = k, j ranges over 0..k−1, so j < k always holds and the item is admitted with probability 1 instead of k/(k+1). In general the admission probability becomes k/i instead of k/(i+1). The inductive step fails because the new item's probability is not k/(t+1). The eviction probability for old items also becomes 1/i, so their survival factor no longer cancels to give k/(t+1).
Exercise
A sampler for n = 4, k = 2 returns {0,1} or {2,3}, each with probability 1/2. Does every item have inclusion probability k/n? Is it a uniform sample without replacement?
Show answer
Each item has probability 1/2 = 2/4, so the marginals are correct. It is not uniform: only 2 of the C(4,2) = 6 subsets can occur, and pairs such as {0,2} have probability 0 instead of 1/6.