Sub topic 7
Cost Analysis: O(n) Time, O(k) Space, and Expected Replacements
This chapter assumes you know Algorithm R from the earlier chapter, are comfortable with Big-O notation, and remember that the harmonic sum 1 + 1/2 + … + 1/n grows like ln n. The goal is to put numbers on three costs: how long Algorithm R runs, how much memory it holds, and how many random numbers and reservoir writes it uses.
Time: One Constant-Cost Step per Item
Algorithm R looks at each item once. For each item it does a fixed amount of work: one comparison, plus one random draw and at most one write after the first k items. No step depends on the reservoir size or on how much of the stream has already gone by. The total time is therefore O(n), with a small constant.
This is optimal for any exact sampler that reads the stream. The last item must end up in the sample with probability k/n, so the algorithm has to look at it. It also cannot skip items blindly, because it doesn't know where the stream ends.
Space: The Reservoir and a Counter
Memory use is k slots for the reservoir plus one integer for the index i. That is O(k) space, independent of n. The counter takes O(log n) bits, which is negligible in practice. A Python int handles any length, and a 64-bit counter overflows only after about 1.8 × 10^19 items.
Random Numbers and Expected Replacements
After the reservoir fills, every item costs one call to the random number generator. That is n − k calls in total, which is often the most expensive part of the loop.
Writes to the reservoir are much rarer. Item i (1-based, i > k) replaces a slot with probability k/i, so by linearity of expectation:
E[replacements] = Σ from i=k+1 to n of k/i = k(Hn − Hk) ≈ k ln(n/k)
The number of writes grows only logarithmically in n.
| n | k | Random calls (n − k) | Expected replacements ≈ k ln(n/k) |
|---|---|---|---|
| 10,000 | 100 | 9,900 | 461 |
| 1,000,000 | 100 | 999,900 | 921 |
| 1,000,000,000 | 100 | ≈ 10^9 | 1,612 |
The gap in this table is large. A billion random draws produce only about 1,600 useful writes. Algorithm L, covered later, removes that gap.
Measuring It
The script below counts replacements and compares the count with the exact formula.
import random
def reservoir_sample_counted(stream, k, rng=random):
reservoir, replacements = [], 0
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
replacements += 1
return reservoir, replacements
def harmonic(m):
return sum(1.0 / t for t in range(1, m + 1))
n, k, trials = 100_000, 50, 20
avg = sum(reservoir_sample_counted(range(n), k)[1] for _ in range(trials)) / trials
print("observed mean:", avg)
print("expected :", k * (harmonic(n) - harmonic(k)))The observed mean should land within a few percent of about 380.
Summary of Costs
| Resource | Cost |
|---|---|
| Time | O(n) |
| Space | O(k) items + one counter |
| Random numbers | n − k |
| Reservoir writes (expected) | k(H_n − H_k) ≈ k ln(n/k) |
Exercise
You sample k = 1,000 items from a stream of n = 10^8 events. Roughly how many reservoir replacements do you expect, and how many random numbers does Algorithm R draw?
Show answer
Expected replacements ≈ k ln(n/k) = 1,000 × ln(10^5) ≈ 1,000 × 11.5 ≈ 11,500. Algorithm R draws n − k ≈ 99,999,000 random numbers, about 8,700 draws per replacement.
Exercise
Why does doubling the stream length add only about k ln 2 expected replacements, no matter how long the stream already is?
Show answer
The extra items n+1 through 2n contribute Σ k/i over that range, which is k(H2n − Hn) ≈ k ln 2 ≈ 0.69k. This amount does not depend on n.