Sub topic 11
Sampling by Random Keys: Keep the k Best
This chapter assumes you know Algorithm R and its k/n correctness argument, Python's heapq module, and the idea that independent continuous random variables tie with probability zero. It covers a second way to build a uniform reservoir. This version is slower than Algorithm R, but it records extra information that later chapters reuse.
The idea: tag every item with a random number
Give each item an independent key drawn uniformly from [0, 1). After the stream ends, keep the k items with the smallest keys. That set is a uniform sample without replacement.
The argument uses symmetry. Each key is i.i.d. and continuous, so every ordering of the n keys is equally likely. That makes every k-subset equally likely to hold the k smallest keys. Each item therefore lands in the sample with probability k/n. The proof needs no induction, because no step in it depends on when an item arrived.
You can also keep the k largest keys. The result is the same distribution. This chapter uses smallest because merging code usually follows that convention.
Doing it in one pass
The stream itself is never stored. You only need the k smallest keys seen so far. A max-heap of size k does this job: its root is the largest key still in the reservoir, so a new key only has to beat the root. Python's heapq is a min-heap, so the code stores negated keys.
import heapq
import random
def keyed_reservoir(stream, k, rng=random):
heap = [] # max-heap via negation: (-key, index, item)
for idx, item in enumerate(stream):
key = rng.random()
if len(heap) < k:
heapq.heappush(heap, (-key, idx, item))
elif key < -heap[0][0]:
heapq.heapreplace(heap, (-key, idx, item))
# Return (key, item) pairs so the keys stay available
return sorted((-neg, item) for neg, _, item in heap)
sample = keyed_reservoir(range(1000), 5, random.Random(42))
print(sample)heapq.nsmallest(k, ((rng.random(), x) for x in stream), key=lambda p: p[0]) does the same thing in one line. It also uses O(k) memory and consumes the iterator lazily.
Cost compared with Algorithm R
| Property | Algorithm R | Random keys |
|---|---|---|
| Random numbers | one per item | one per item |
| Time per item | O(1) | O(1) to compare, O(log k) to replace |
| Expected replacements | about k·ln(n/k) | about k·ln(n/k) |
| Memory | k items | k items plus k keys |
| Keeps keys | no | yes |
Item i (0-based) enters the heap with probability k/(i+1), the same rate as in Algorithm R. So the expected total time is O(n + k log k · log(n/k)), and for large n the linear scan dominates.
Why keep the keys
The keys turn the sample into a record you can reuse:
- Changing how keys are generated changes the distribution. The weighted chapter uses this.
- Two reservoirs built with the same rule combine correctly by keeping the k smallest keys of their union. The merging chapter shows this.
- Sorting by key gives a uniformly random order of the sample at no extra cost.
Common errors
- Comparing items on ties. If two entries have equal keys, a heap of
(key, item)tuples falls back to comparing the items, which fails for dicts and other unorderable types. Put the index in the middle of the tuple to break ties. - Reusing one key across streams. Keys must be independent per item. If you seed a fresh RNG with the same value for each partition, every partition gets the same key sequence.
- Mixing conventions. If one part of the system keeps the smallest keys and another keeps the largest, merged samples come out biased. Choose one convention and document it.
- Returning items without keys. Once the keys are dropped, the reservoir can no longer be merged with others.
Exercise
You run keyed_reservoir on a stream of n = 10 items with k = 3, but you mistakenly draw keys with rng.randint(0, 1) instead of rng.random(). Is the sample still uniform, and why?
Show answer
No. With only two possible keys, ties are common. heapq then orders tied entries by index, and the strict < comparison never lets a later item with an equal key replace one already in the heap. Earlier items are favored, so inclusion is no longer 3/10 per item. The symmetry argument needs continuous keys, where ties have probability zero.
Exercise
Why does the streaming version use a max-heap (negated keys) when the goal is to keep the k smallest keys?
Show answer
Each new key only needs to be compared with the largest key currently kept, because that entry is the one to evict. A max-heap exposes that key at the root in O(1), and heapreplace swaps it out in O(log k).