Sub topic 7
Cost Analysis: O(n) Time, O(k) Space, and Expected Replacements
This chapter measures what Algorithm R costs. It assumes you have the Algorithm R code from the earlier chapter, are comfortable with Big-O notation, and know that the expected value of a sum is the sum of the expected values (linearity of expectation). It also uses harmonic numbers, which are defined below.
There are four costs to track:
- Time: how much work the algorithm does per item and in total.
- Space: how much memory it holds at any moment.
- Random-number calls: how often it asks the random number generator (RNG) for a value.
- Replacements: how often it actually writes a new item into the reservoir.
For uniform sampling, the first two are already as small as they can be. The last two differ by a large factor, and that gap is the reason faster variants exist.
The Algorithm Under Measurement
Here is Algorithm R again, for reference:
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 loop has two phases. In the fill phase, the first k items go straight into the list. In the replacement phase, every later item costs one random draw, and the item is written into the reservoir only when the draw falls below k.
Time: O(n), and Why That Is Optimal Here
Each loop iteration does a constant amount of work: one counter increment, one comparison, at most one RNG call, and at most one list assignment. A Python list assignment by index is O(1). Over n items the total is O(n), and the constant does not depend on k.
You cannot do better than O(n) when the stream is a plain iterator. To reach item n, you have to pull items 1 through n − 1 out of the iterator, even if you throw them away at once. What you can reduce is the work done on each item. Algorithm R pays for one RNG call per item. A later chapter shows how Algorithm L skips over items with no per-item RNG call. If the source supports real random access, such as seeking to a byte offset in a file of fixed-size records, skipping can even make the total time sublinear.
Space: O(k)
At any moment, Algorithm R holds:
- the reservoir, which contains at most k items,
- the counter
i, plus the temporariesjanditem.
That gives O(k) items of memory. Two details matter in practice:
- The bound counts items, not bytes. If items vary in size, the memory bound is k times the largest item seen. A reservoir of 1,000 log lines is small. A reservoir of 1,000 uploaded files is not.
- The counter grows slowly. Strictly, storing
itakes O(log n) bits. Python integers grow as needed, and in fixed-width languages a 64-bit counter is enough for any stream you will meet. In practice it is a constant.
When n < k, the reservoir just holds all n items, which is still within O(k).
Random-Number Calls: Exactly n − k
The fill phase makes no RNG calls. The replacement phase makes exactly one call per item. So for n ≥ k:
- RNG calls = n − k.
This count is deterministic. Each call usually costs more than the rest of the loop body, because it involves generator state updates and range reduction to produce an unbiased integer. In CPython, random.randint is noticeably slower than a bare loop iteration, so for large streams the RNG often dominates the run time.
Replacements: About k ln(n/k)
Now count how many times the line reservoir[j] = item runs.
Use 1-based positions. The item at position i, for i > k, is written into the reservoir with probability k/i, because the draw j is uniform over i values and k of them are accepted. Let Xi be 1 if item i causes a replacement and 0 otherwise. Then E[Xi] = k/i, and by linearity of expectation:
E[replacements] = sum over i from k+1 to n of k/i = k (Hn − Hk)
Here Hm = 1 + 1/2 + … + 1/m is the m-th harmonic number. A standard approximation is Hm ≈ ln m + 0.5772, so the constant cancels in the difference:
E[replacements] ≈ k ln(n/k)
This number grows only logarithmically in n. The following table compares it with the RNG calls for k = 100:
| Stream length n | RNG calls (n − k) | Expected replacements k(H_n − H_k) | Share of calls that cause a write |
|---|---|---|---|
| 1,000 | 900 | ≈ 229.8 | 25.5% |
| 10,000 | 9,900 | ≈ 460.0 | 4.6% |
| 100,000 | 99,900 | ≈ 690.3 | 0.69% |
| 1,000,000 | 999,900 | ≈ 920.5 | 0.092% |
| 1,000,000,000 | 999,999,900 | ≈ 1,611.3 | 0.00016% |
On a billion-item stream, Algorithm R draws about a billion random numbers to make about 1,600 changes. Almost every draw only confirms "keep the current reservoir".
How Tightly Replacements Concentrate
Each Xi depends only on its own fresh draw j, so the Xi are independent Bernoulli variables. Their variance is:
Var[replacements] = sum of (k/i)(1 − k/i), which is less than E[replacements]
The standard deviation is therefore at most the square root of the mean. For n = 10^6 and k = 100, the mean is about 920 and the standard deviation is under about 30. A single run will almost always land within a few percent of the formula.
Where Replacements Happen
Replacements cluster early in the stream. The expected number of replacements between positions a and b is about k ln(b/a). So positions 1,000 to 10,000 contribute as many expected writes as positions 100,000 to 1,000,000. The reservoir changes quickly at first and then settles. This matters if each write is expensive, for example if it copies a large record or updates an index on disk.
Measuring It
The following script instruments Algorithm R, runs it several times, and compares the measured counts with the formulas.
import random
import statistics
def reservoir_sample_counted(stream, k, rng=random):
reservoir = []
rng_calls = 0
replacements = 0
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # inclusive: 0..i
rng_calls += 1
if j < k:
reservoir[j] = item
replacements += 1
return reservoir, rng_calls, replacements
def expected_replacements(n, k):
# 1-based positions k+1..n, each replaced with probability k/i
return sum(k / i for i in range(k + 1, n + 1))
def expected_variance(n, k):
return sum((k / i) * (1 - k / i) for i in range(k + 1, n + 1))
if __name__ == "__main__":
rng = random.Random(12345)
n, k, trials = 100_000, 100, 30
calls_seen = set()
reps = []
for _ in range(trials):
_, calls, r = reservoir_sample_counted(range(n), k, rng)
calls_seen.add(calls)
reps.append(r)
print("RNG calls per run:", calls_seen, "expected:", n - k)
print("mean replacements: %.1f" % statistics.mean(reps))
print("expected: %.1f" % expected_replacements(n, k))
print("stdev replacements: %.1f" % statistics.stdev(reps))
print("expected stdev: %.1f" % expected_variance(n, k) ** 0.5)The RNG-call set always contains the single value 99,900. The mean number of replacements comes out close to 690, and the standard deviation is about 26, which matches the variance formula.
Summary of Costs
| Resource | Algorithm R cost | Can it be reduced? |
|---|---|---|
| Items read | n | No, not for a sequential iterator |
| Time | O(n), independent of k | The per-item constant can be reduced |
| Memory | O(k) items | No, the sample itself needs k slots |
| RNG calls | exactly n − k | Yes, to about O(k(1 + log(n/k))) with skipping |
| Reservoir writes | expected k(H_n − H_k) ≈ k ln(n/k) | Already minimal: each write is necessary |
The last two rows explain what to do next. Writes are already as few as they can be, because each one reflects a real change in the sample. RNG calls are wasteful by a factor of about n / (k ln(n/k)). An algorithm that can predict when the next write happens, instead of testing every item, can draw random numbers about as often as it writes. That is the idea behind Algorithm L.
Exercise
For k = 50 and n = 50,000, estimate the expected number of reservoir replacements made by Algorithm R, and the number of RNG calls.
Show answer
Expected replacements ≈ k ln(n/k) = 50 × ln(1000) ≈ 50 × 6.908 ≈ 345. RNG calls are exactly n − k = 49,950.
Exercise
Show that the expected number of replacements in positions n+1 through 2n is about k ln 2, no matter how large n is.
Show answer
The sum of k/i for i from n+1 to 2n equals k(H2n − Hn), which is about k(ln 2n − ln n) = k ln 2 ≈ 0.693k. Each doubling of the stream adds about 0.69k expected writes.
Exercise
A colleague says that because only about k ln(n/k) items ever enter the reservoir, Algorithm R should run in O(k log(n/k)) time on a Python generator. Why is this wrong, and what does the bound actually limit?
Show answer
A generator can only be advanced one item at a time, so reaching the last item requires producing all n items, which takes Ω(n) time. The k log(n/k) bound limits reservoir writes, and with a skip-based method it also limits RNG calls. It does not limit the cost of reading the stream.
Exercise
Why is the variance of the replacement count less than its mean, and what does that imply for a single run with n = 10^6 and k = 100?
Show answer
Each X_i is an independent Bernoulli variable with p = k/i, so its variance p(1 − p) is less than p. Summing gives a variance less than the mean, about 920. The standard deviation is therefore below about 30, so a single run is very likely to make between roughly 860 and 980 replacements.