Video in progress

How do you pick K elements with equal probability from a stream of unknown length, in a single pass?

Reservoir sampling: I take the first K, then accept the i-th element (counting from 1) with probability K/i and put it in place of a random element in the reservoir. In the end each element remains with probability K/n, and memory is O(K).

📖 Answer

static <T> List<T> sample(Iterator<T> stream, int k, RandomGenerator rnd) {
    List<T> reservoir = new ArrayList<>(k);
    int seen = 0;
    while (stream.hasNext()) {
        T item = stream.next();
        seen++;
        if (reservoir.size() < k) {
            reservoir.add(item);
        } else {
            int j = rnd.nextInt(seen);       // 0..seen-1
            if (j < k) reservoir.set(j, item);
        }
    }
    return reservoir;
}

Why is it uniform? The i-th element gets in with probability K/i. The next one, element (i+1), pushes it out with probability (K/(i+1)) × (1/K) = 1/(i+1), so its probability of staying is i/(i+1). The products telescope and K/n remains. In an interview they ask for this proof in a sentence or two.

A common mistake is rnd.nextInt(seen + 1) or comparing against nextInt(k). The distribution skews in a barely noticeable way, and a test won't catch it. That's why I write a statistical test for code like this: run it a million times and check each position's frequency with a chi-squared test.

Where you'll need it:

  • keeping 0.1% of logs for debugging, but exactly K of them even if the stream volume changes over the day;
  • a random sample from a large table: ORDER BY random() LIMIT k reads the whole table on every query and computes random() for every row;
  • in the distributed case: each node sends its reservoir and the count it has seen, and the center merges them with weights.

If the elements are weighted (say big customers should be picked more often), there is the A-Res algorithm: give each element the key u^(1/w) and keep the K largest in a heap.

Since Java 17 there is the RandomGenerator interface; in multi-threaded code use ThreadLocalRandom, because a shared Random causes contention.