TExcelTAD
Home › Foundations of Algorithm Analysis › Balls into Bins, Coupons and Streaks

Balls into Bins, Coupons and Streaks

Throw mm balls, one at a time, each into one of nn 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 1−1n1 - \frac{1}{n}, and the balls are independent, so all mm miss it with probability (1−1n)m\left(1 - \frac{1}{n}\right)^m. With one indicator per bin,

E[empty bins]=n(1−1n)m≈ne−m/n\mathbb{E}[\text{empty bins}] = n\left(1 - \frac{1}{n}\right)^m \approx n e^{-m/n}

With as many balls as bins (m=nm = n), about n/en/e, 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.

python · try it yourself
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 nn different coupons in every box, uniformly at random. How many boxes do you expect to buy before you own all nn? This is the coupon collector's problem: balls until no bin is empty.

Split the process into phases. Phase ii (for i=0,…,n−1i = 0, \ldots, n-1) starts when exactly ii bins have been hit and ends with the ball that hits a new one. During phase ii each ball hits a new bin with probability pi=n−inp_i = \frac{n-i}{n}, independently, so the length of the phase is a geometric random variable with mean 1pi=nn−i\frac{1}{p_i} = \frac{n}{n-i}. By linearity, the expected total is

E[balls]=∑i=0n−1nn−i=n(1n+1n−1+⋯+11)=nHn=nln⁡n+O(n)\mathbb{E}[\text{balls}] = \sum_{i=0}^{n-1} \frac{n}{n-i} = n\left(\frac{1}{n} + \frac{1}{n-1} + \cdots + \frac{1}{1}\right) = n H_n = n \ln n + O(n)

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 nn balls on average.

python · try it yourself
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 nn of them needs Θ(nlog⁡n)\Theta(n \log n) probes, a factor ln⁡n\ln n more than visiting them in order.

The fullest bin

With m=nm = n 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 nn grows):

  • One random bin per ball: the maximum load is (1+o(1))ln⁡nln⁡ln⁡n(1 + o(1)) \dfrac{\ln n}{\ln \ln n}, which is Θ(log⁡nlog⁡log⁡n)\Theta\left(\frac{\log n}{\log \log n}\right). 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 ln⁡ln⁡nln⁡2+O(1)\dfrac{\ln \ln n}{\ln 2} + O(1).

The second result is striking. One extra random probe per ball improves the maximum load from roughly log⁡n/log⁡log⁡n\log n / \log\log n to log⁡log⁡n\log\log n, an exponential improvement, and a third choice only changes the constant (ln⁡ln⁡n/ln⁡d\ln\ln n / \ln d for dd 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.

One random bin per ball30 balls, 9 bins emptymax 630 binsLess loaded of two random bins30 balls, 4 bins emptymax 330 bins

The same comparison for larger nn, averaged over a few seeded runs:

python · try it yourself
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 ln⁡n/ln⁡ln⁡n\ln n / \ln\ln n because the o(1)o(1) correction shrinks very slowly. What the table shows clearly is the gap between the two columns, which widens as nn grows.

Proof sketch: the one-choice upper bound

A fixed bin gets at least kk of the nn balls with probability at most (nk)n−k≤1k!\binom{n}{k} n^{-k} \le \frac{1}{k!} (choose which kk balls land there). By a union bound over the nn bins, Pr⁡[max load≥k]≤nk!\Pr[\text{max load} \ge k] \le \frac{n}{k!}. With k=3ln⁡nln⁡ln⁡nk = \frac{3\ln n}{\ln\ln n}, Stirling's formula gives k!≥n2k! \ge n^2 for large nn, so the probability is at most 1n\frac{1}{n}. 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 nn 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 lg⁡n\lg n (log⁡2n\log_2 n).

Upper bound. A run of at least rr heads starting at a given position has probability 2−r2^{-r}. There are fewer than nn starting positions, so by a union bound Pr⁡[some run≥r]≤n2−r\Pr[\text{some run} \ge r] \le n 2^{-r}. For r=2lg⁡nr = 2\lg n this is n⋅n−2=1nn \cdot n^{-2} = \frac{1}{n}: runs twice as long as lg⁡n\lg n are rare.

Lower bound. Cut the nn flips into n/rn/r disjoint blocks of length r=12lg⁡nr = \frac{1}{2}\lg n. A block is all heads with probability 2−r=n−1/22^{-r} = n^{-1/2}, independently of the other blocks, so the chance that no block is all heads is (1−n−1/2)n/r≤e−n/r\left(1 - n^{-1/2}\right)^{n/r} \le e^{-\sqrt{n}/r}, which tends to 0. So runs of 12lg⁡n\frac{1}{2}\lg n almost surely occur, and the expected longest run is Θ(lg⁡n)\Theta(\lg n).

A dynamic program computes the exact distribution. It tracks the length of the current run of heads, never allowing it to reach rr, which gives Pr⁡[no run of r]\Pr[\text{no run of } r]; then E[L]=∑r≥1Pr⁡[L≥r]\mathbb{E}[L] = \sum_{r \ge 1} \Pr[L \ge r].

python · try it yourself
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:

cpp · try it yourself
#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 lg⁡n\lg n 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 lg⁡n\lg n, which is a simple way to spot fake data.

Test yourself

nn balls are thrown into nn bins uniformly at random. About what fraction of the bins stays empty for large nn?

  1. None
  2. 12\frac{1}{2}
  3. 1e≈0.37\frac{1}{e} \approx 0.37
  4. 1n\frac{1}{n}

What is the expected number of balls until all nn bins have been hit (the coupon collector)?

  1. nn
  2. 2n2n
  3. nHn=nln⁡n+O(n)n H_n = n \ln n + O(n)
  4. n2n^2

With m=nm = n balls, how does the maximum load change if every ball goes into the less loaded of two random bins instead of one random bin?

  1. It halves
  2. It drops from Θ(log⁡n/log⁡log⁡n)\Theta(\log n / \log\log n) to log⁡log⁡n/ln⁡2+O(1)\log\log n / \ln 2 + O(1)
  3. It does not change
  4. It drops to exactly 1

Why is a run of 2lg⁡n2\lg n heads in nn fair flips unlikely?

  1. Because runs never exceed lg⁡n\lg n
  2. By a union bound over fewer than nn start positions, each starting such a run with probability 2−2lg⁡n=n−22^{-2\lg n} = n^{-2}, so the probability is at most 1n\frac{1}{n}
  3. Because the flips are dependent
  4. By the coupon collector bound