Balls into Bins, Coupons and Streaks
Throw balls, one at a time, each into one of bins chosen uniformly at random and independently of the others. This toy model is everywhere in computer science: the balls are keys and the bins are hash-table slots, or the balls are jobs and the bins are servers, or the balls are requests and the bins are cache lines. Three questions about it come up again and again. How many bins stay empty? How many balls until no bin is empty? How full does the fullest bin get? This lesson answers all three, then applies the same reasoning to a related question: how long is the longest run of heads in a sequence of coin flips?
The Birthday Paradox was already a balls-and-bins question: "is there a bin with two balls?" Everything here uses indicator variables and linearity (Indicator Random Variables) plus the geometric distribution.
Empty bins
Fix a bin. One ball misses it with probability , and the balls are independent, so all miss it with probability . With one indicator per bin,
With as many balls as bins (), about , roughly 37%, of the bins are still empty. A hash table with as many keys as slots leaves more than a third of its slots unused, while others hold several keys.
import random
def throw(n, m, rng):
loads = [0] * n
for _ in range(m):
loads[rng.randrange(n)] += 1
return loads
rng = random.Random(7)
n = 100
for m in [50, 100, 200, 460]:
trials = 500
empty = sum(throw(n, m, rng).count(0) for _ in range(trials)) / trials
print(f"n = {n}, m = {m:3}: empty bins simulated {empty:6.2f}, formula n(1 - 1/n)^m = {n * (1 - 1 / n) ** m:6.2f}")n = 100, m = 50: empty bins simulated 60.52, formula n(1 - 1/n)^m = 60.50
n = 100, m = 100: empty bins simulated 36.76, formula n(1 - 1/n)^m = 36.60
n = 100, m = 200: empty bins simulated 13.61, formula n(1 - 1/n)^m = 13.40
n = 100, m = 460: empty bins simulated 1.02, formula n(1 - 1/n)^m = 0.98
Even 460 balls, more than four per bin on average, still leave about one bin empty. That leads to the next question.
How many balls until every bin is hit: the coupon collector
A cereal brand hides one of different coupons in every box, uniformly at random. How many boxes do you expect to buy before you own all ? This is the coupon collector's problem: balls until no bin is empty.
Split the process into phases. Phase (for ) starts when exactly bins have been hit and ends with the ball that hits a new one. During phase each ball hits a new bin with probability , independently, so the length of the phase is a geometric random variable with mean . By linearity, the expected total is
The same harmonic number as in The Hiring Problem, for a different reason. The phases are very uneven: the first few take one ball each, and the last one alone takes balls on average.
import random
def balls_until_full(n, rng):
seen, balls, phases = set(), 0, []
since = 0
while len(seen) < n:
balls += 1
since += 1
b = rng.randrange(n)
if b not in seen:
seen.add(b)
phases.append(since) # balls spent in this phase
since = 0
return balls, phases
rng = random.Random(7)
n, trials = 50, 2000
total = 0
phase_sum = [0] * n
for _ in range(trials):
balls, phases = balls_until_full(n, rng)
total += balls
for i, p in enumerate(phases):
phase_sum[i] += p
H = sum(1 / k for k in range(1, n + 1))
print(f"n = {n}: every bin hit after {total / trials:.1f} balls on average, n H_n = {n * H:.1f}")
for i in [0, 1, 25, 48, 49]:
print(f" phase {i:2}: average {phase_sum[i] / trials:6.2f} balls, n/(n - i) = {n / (n - i):6.2f}")n = 50: every bin hit after 224.1 balls on average, n H_n = 225.0
phase 0: average 1.00 balls, n/(n - i) = 1.00
phase 1: average 1.02 balls, n/(n - i) = 1.02
phase 25: average 1.99 balls, n/(n - i) = 2.00
phase 48: average 24.49 balls, n/(n - i) = 25.00
phase 49: average 50.10 balls, n/(n - i) = 50.00
In algorithm terms: a randomized procedure that probes random positions until it has seen all of them needs probes, a factor more than visiting them in order.
The fullest bin
With balls the average load is exactly 1, but the maximum is not. Two classical results describe it (each holds with probability tending to 1 as grows):
- One random bin per ball: the maximum load is , which is . For a hash table with chaining, that is the length of the longest chain when the load factor is 1.
- The power of two choices: if each ball looks at two random bins and goes into the less loaded one, the maximum load drops to .
The second result is striking. One extra random probe per ball improves the maximum load from roughly to , an exponential improvement, and a third choice only changes the constant ( for choices). Load balancers, cuckoo hashing and distributed caches use this idea.
The lab below throws the balls one per frame, with the same random stream for both strategies (the two-choice side uses the one-choice side's bin as its first candidate). With the default 30 bins and 30 balls, run 1 ends with a fullest bin of 6 on the left and 3 on the right; with 60 bins and 300 balls it is 16 against 6. Try several runs: the left side varies a lot, the right side hardly at all.
The same comparison for larger , averaged over a few seeded runs:
import random
from math import log
def max_loads(n, rng):
one = [0] * n
two = [0] * n
for _ in range(n): # m = n balls
a, b = rng.randrange(n), rng.randrange(n)
one[a] += 1
two[b if two[b] < two[a] else a] += 1 # the less loaded of two random bins
return max(one), max(two)
rng = random.Random(7)
print(" n one choice two choices ln n/ln ln n ln ln n/ln 2")
for n in [10, 100, 1000, 10000, 100000]:
trials = 20 if n <= 10000 else 3
res = [max_loads(n, rng) for _ in range(trials)]
m1 = sum(r[0] for r in res) / trials
m2 = sum(r[1] for r in res) / trials
print(f"{n:7} {m1:11.2f} {m2:11.2f} {log(n) / log(log(n)):12.2f} {log(log(n)) / log(2):12.2f}") n one choice two choices ln n/ln ln n ln ln n/ln 2
10 3.15 2.10 2.76 1.20
100 4.30 2.40 3.02 2.20
1000 5.30 3.00 3.57 2.79
10000 6.70 3.20 4.15 3.20
100000 7.67 3.67 4.71 3.53
The leading terms are only the leading terms: the measured one-choice maximum sits well above because the correction shrinks very slowly. What the table shows clearly is the gap between the two columns, which widens as grows.
Proof sketch: the one-choice upper bound
A fixed bin gets at least of the balls with probability at most (choose which balls land there). By a union bound over the bins, . With , Stirling's formula gives for large , so the probability is at most . The matching lower bound and the two-choice bound need more care (the second-moment method and a layered induction, respectively).
Streaks of heads
Flip a fair coin times. How long is the longest run of consecutive heads? Think of it as a check on a random-number generator, or as the longest unlucky stretch of a randomized algorithm. The answer is about ().
Upper bound. A run of at least heads starting at a given position has probability . There are fewer than starting positions, so by a union bound . For this is : runs twice as long as are rare.
Lower bound. Cut the flips into disjoint blocks of length . A block is all heads with probability , independently of the other blocks, so the chance that no block is all heads is , which tends to 0. So runs of almost surely occur, and the expected longest run is .
A dynamic program computes the exact distribution. It tracks the length of the current run of heads, never allowing it to reach , which gives ; then .
from math import log2
def prob_no_run(n, r):
# Pr[n fair flips contain no run of r heads]; state = length of the current run of heads
dist = [1.0] + [0.0] * (r - 1)
for _ in range(n):
new = [0.0] * r
for run, p in enumerate(dist):
new[0] += p / 2 # tails resets the run
if run + 1 < r:
new[run + 1] += p / 2 # heads extends it (a run of r is not allowed)
dist = new
return sum(dist)
def expected_longest_run(n):
# E[L] = sum over r >= 1 of Pr[L >= r]
total, r = 0.0, 1
while True:
p_at_least = 1 - prob_no_run(n, r)
if p_at_least < 1e-12:
return total
total += p_at_least
r += 1
for n in [16, 64, 256, 1024]:
print(f"n = {n:4}: expected longest run of heads {expected_longest_run(n):5.2f}, lg n = {log2(n):4.1f}")
n = 1024
for r in [5, 8, 10, 12, 15, 20]:
print(f" Pr[some run of {r:2} heads in {n} flips] = {1 - prob_no_run(n, r):.4f}")n = 16: expected longest run of heads 3.43, lg n = 4.0
n = 64: expected longest run of heads 5.36, lg n = 6.0
n = 256: expected longest run of heads 7.34, lg n = 8.0
n = 1024: expected longest run of heads 9.33, lg n = 10.0
Pr[some run of 5 heads in 1024 flips] = 1.0000
Pr[some run of 8 heads in 1024 flips] = 0.8676
Pr[some run of 10 heads in 1024 flips] = 0.3926
Pr[some run of 12 heads in 1024 flips] = 0.1166
Pr[some run of 15 heads in 1024 flips] = 0.0153
Pr[some run of 20 heads in 1024 flips] = 0.0005
In C++
The same dynamic program in C++. It does the same floating-point operations in the same order, so it prints the same numbers:
#include <cmath>
#include <cstdio>
#include <vector>
using namespace std;
// Pr[n fair flips contain no run of r heads]; state = length of the current run of heads
double prob_no_run(int n, int r) {
vector<double> dist(r, 0.0);
dist[0] = 1.0;
for (int flip = 0; flip < n; flip++) {
vector<double> next(r, 0.0);
for (int run = 0; run < r; run++) {
double p = dist[run];
next[0] += p / 2; // tails resets the run
if (run + 1 < r)
next[run + 1] += p / 2; // heads extends it (a run of r is not allowed)
}
dist = next;
}
double total = 0;
for (double p : dist) total += p;
return total;
}
// E[L] = sum over r >= 1 of Pr[L >= r]
double expected_longest_run(int n) {
double total = 0;
for (int r = 1;; r++) {
double p_at_least = 1 - prob_no_run(n, r);
if (p_at_least < 1e-12) return total;
total += p_at_least;
}
}
int main() {
for (int n : {16, 64, 256, 1024})
printf("n = %4d: expected longest run of heads %5.2f, lg n = %4.1f\n",
n, expected_longest_run(n), log2(n));
int n = 1024;
for (int r : {5, 8, 10, 12, 15, 20})
printf(" Pr[some run of %2d heads in %d flips] = %.4f\n", r, n, 1 - prob_no_run(n, r));
}n = 16: expected longest run of heads 3.43, lg n = 4.0
n = 64: expected longest run of heads 5.36, lg n = 6.0
n = 256: expected longest run of heads 7.34, lg n = 8.0
n = 1024: expected longest run of heads 9.33, lg n = 10.0
Pr[some run of 5 heads in 1024 flips] = 1.0000
Pr[some run of 8 heads in 1024 flips] = 0.8676
Pr[some run of 10 heads in 1024 flips] = 0.3926
Pr[some run of 12 heads in 1024 flips] = 0.1166
Pr[some run of 15 heads in 1024 flips] = 0.0153
Pr[some run of 20 heads in 1024 flips] = 0.0005
The expected longest run tracks closely, about two thirds below it, and the distribution is tight: in 1,024 flips a run of 5 heads is practically certain and a run of 20 is very unlikely. People asked to write down "random" flips by hand almost never include a run as long as , which is a simple way to spot fake data.
Test yourself
balls are thrown into bins uniformly at random. About what fraction of the bins stays empty for large ?
- None
What is the expected number of balls until all bins have been hit (the coupon collector)?
With balls, how does the maximum load change if every ball goes into the less loaded of two random bins instead of one random bin?
- It halves
- It drops from to
- It does not change
- It drops to exactly 1
Why is a run of heads in fair flips unlikely?
- Because runs never exceed
- By a union bound over fewer than start positions, each starting such a run with probability , so the probability is at most
- Because the flips are dependent
- By the coupon collector bound