Balls, bins & birthdays
Throw balls independently and uniformly into bins. That single experiment — the occupancy model— contains the birthday paradox, hash collisions, the coupon collector, load balancing, and the statistics of empty slots, all as different questions asked of the same picture. This chapter develops the model’s four classic questions — when do collisions appear, how many bins stay empty, how loaded is the fullest bin, and how long until no bin is empty — and extracts the scaling laws (, , , ) that every one of those applications runs on.
Almost every “random allocation” problem is the same experiment wearing a costume. People into days of the year: birthdays. Keys into hash slots: collisions. Die rolls into faces: coupon collecting. Trades into time buckets, jobs into servers, strategies into regimes — all balls into bins. What changes is the question: the birthday problem asks for the first collision (answer: around balls), the empty-bins problem asks what fraction of bins stay untouched (answer: ), the load-balancing problem asks how bad the worst bin is (answer: at ), and the coupon collector asks when the last bin fills (answer: ). Learn the picture once and the four answers become one mental model — plus a single computational trick, indicators and linearity, that derives most of them in a line.
The occupancy model#
Formally: balls land in bins chosen independently and uniformly from . Write for the load of bin — the number of balls it receives. Each (common distributions), the loads sum to exactly, and they are not independent — a ball in bin 1 is a ball denied to bin 2. The whole subject is the interplay between the marginal (binomial, easy) and the joint (constrained, subtle), and the recurring strategy is to dodge the joint entirely — with linearity of expectation (expectation & linearity) for “how many bins/pairs/days” questions, the union bound (inequalities & bounds) for “does any bin misbehave” questions, and Poissonisation (below) when a genuine joint statement is unavoidable.
The regime that matters is set by the ratio and by : collisions are governed by pairs of balls (there are of them, each colliding with probability ), while occupancy is governed by balls per bin. Keep those two dials separate and the scaling laws below stop being surprising.
Birthdays revisited: the √n law#
The basic computation — 23 people suffice for a 50% chance of a shared birthday — is worked in counting & combinatorics. Here we explain the scaling, because the exact number 23 is a consequence of a law worth far more than it. With balls and bins,
using for small . The exponent is the expected number of colliding pairs, and that is no coincidence:
For each of the pairs of balls, let . Whatever bin ball chose, ball matches it with probability , so . Linearity — dependence between pairs be damned — gives
Collisions become likely precisely when this expectation reaches order 1 — i.e. when , the solution of . For : , and indeed 23 people give collision probability . Check the exponent: at the expected pair count is — the 50% threshold is exactly where the expected number of collisions hits .
The moral: collisions appear at , not , because pairs grow quadratically in . Nobody needs to hit your birthday (that takes people for a 50% chance); someone only needs to hit someone’s, and there are chances among 23 people. The same quadratic is the birthday attack in cryptography: finding some pair of inputs with the same hash — enough to forge a signature — takes only attempts against a -bit hash, not . A 64-bit hash resists a preimage hunt at but folds to a collision hunt at — an afternoon of computation. This is why cryptographic hashes are 256 bits: the security level is half the width.

Empty bins and the 37% law#
Now ask the opposite question: which bins receive nothing? Let . Each ball misses bin with probability , independently, so , and linearity gives
At — as many balls as bins — the empty fraction is . Uniform randomness is far lumpier than intuition expects: throw 365 balls at 365 days and about 134 days receive no ball, which forces other days to double and triple up — the empty-bin law and the birthday paradox are two faces of the same clumping. (This coverage number is the same one that says a bootstrap resample touches about 63% of the original data points — resampling & bootstrap.)
Is the fraction actually close to , or only on average? Compute the variance. With ,
since two bins are both empty iff every ball avoids both: . Because , the covariances are negative — one bin being empty leaves more balls to fill the others — and a short expansion shows while . Chebyshev then pins the empty fraction within of with high probability. ■ The simulation below finds the fraction within a third of a percent of already at .

Poissonisation: pretending the bins are independent#
Bin loads are dependent, but barely. The marginal is , and by the law of rare events (common distributions) — many trials, tiny success probability — this converges to with :
The stronger — and more useful — statement is the Poissonisation heuristic: the joint vector of loads behaves like independent variables. Why is that legitimate? If you throw a number of balls instead of exactly , the thinning property of Poisson processes (Poisson processes) makes the loads exactly independent — and a Poisson() count is , a vanishing relative difference — a standard transfer lemma makes the comparison precise at the cost of an factor on probabilities. Sanity checks it passes instantly: expected empty bins (matches), expected singleton bins , expected doubly-occupied days (Problem 2 tests this against the exact count).
The heuristic is trustworthy for bulk statistics — counts of bins with a given load, fractions, maxima — up to the transfer cost. It fails for statements that feel the exact total: the true loads sum to always, Poisson loads only on average, so “the sum of all loads” has variance 0 in reality and under Poissonisation. Never use it on a quantity pinned by the constraint.
Maximum load, and the power of two choices#
Throw balls into bins — average load exactly 1. How bad is the worst bin? The answer is one of the most quoted results in randomised algorithms:
Fix a bin and a level . The chance the bin receives at least named balls is at most (choose which balls, demand each land there, ignore the rest — an over-count, hence an upper bound). Union over all bins (inequalities & bounds):
Take : then , since . The bound becomes . A matching lower bound (via Poissonisation: the chance no bin among near-independent Poisson(1) loads reaches dies once ) shows the order is exact. ■ The rate comes from : factorials beat exponentials, so the max load grows slower than — about 4–5 for , only 8 or so for , as the simulation confirms.
Now the miracle. Change the protocol: for each ball, pick two bins uniformly at random and place the ball in the emptier of the two. The maximum load collapses to
Why one extra glance is worth so much. For a bin to climb to height under two choices, a ball must draw two bins that are both already at height . If a fraction of bins reach height , the chance of that double-draw is — so the fractions square at every level: , giving — doubly exponential decay, hence a maximum at ; with one choice the decay is only factorial. This is why real load balancers sample two servers and route to the shorter queue — nearly all the benefit of full information, at the price of two random probes.
The coupon collector as occupancy#
Final question: how many balls until no bin is empty? That is the coupon collector — each cereal box a ball, each coupon type a bin, collection complete when every bin is hit. The stage decomposition (expectation & linearity, brainteasers) does expectation in three lines: when bins are occupied, each throw hits a new bin with probability , so the wait for the -th new bin is geometric with mean , and
The occupancy view explains the : after throws the expected number of still-empty bins is , which passes through 1 exactly at . The last few coupons cost almost everything — the first half of the bins fill in throws, while the final lone bin alone costs throws on average.
Around the transition is sharp. Writing , the expected empty count is , and by Poissonisation the number of empty bins is approximately Poisson with that mean, so
the Gumbel distribution — the same double-exponential law that governs the maximum of i.i.d. exponentials in order statistics, and no accident: is the maximumover bins of each bin’s first-hit time, and maxima of light-tailed waiting times are Gumbel territory. The fluctuations of around are only — relatively tiny — which is why “have I sampled every state?” questions flip from almost-certainly-no to almost-certainly-yes over a narrow window.
Non-uniform bins only make collisions worse#
Real birthdays are not uniform — September peaks, holidays dip. Does that break the 23-person answer? It strengthens it. Let bin receive each ball with probability . Two independent balls collide with probability
by Jensen’s inequality (inequalities & bounds) applied to the convex function : the average of squares beats the square of the average, strictly unless all are equal. ■ The per-pair statement lifts to the full event: for every group size , the no-collision probability is a Schur-concave function of — maximised at the uniform distribution, so any non-uniformity can only raise the collision probability. Intuitively: skew concentrates balls in the popular bins, and collisions live where the mass piles up.
So the textbook 23 is conservative: with real birthday frequencies the 50% point arrives at 23 or earlier, never later. The same convexity works against you in hashing — a hash function with a biased output distribution collides faster than the uniform analysis promises, by exactly the factor — and in any bucketing scheme where the traffic is skewed: collision risk is priced by (the “collision entropy”), not by the bin count .
Bucketing trades into time bins is the occupancy model verbatim: fills spread over one-minute bars leaves of bars empty even if arrivals are perfectly uniform — so sparse bars are not evidence of regime change, and any per-bar statistic must budget for the 37% law before reading meaning into gaps (Poisson processes is the continuous-time version). Hash-based deduplication of market data feeds is a birthday problem: dedupe messages through a 32-bit fingerprint and the expected number of false merges is — silently dropped ticks; Problem 5 sizes the table properly. And when a desk runs 30 strategies that each fire in a handful of regime-bins, the birthday arithmetic says some pair will “collide” — crowd onto the same trade in the same hour — far sooner than intuition expects, with the rate inflated by because everyone’s signal fires in the same high-vol bins. Correlated books built from “independent” strategies are a non-uniform birthday problem you are on the wrong side of.
Simulation: all four laws at once#
One experiment checks everything: throw balls into bins, then read off the empty fraction, the colliding pairs, and the maximum load — plus the two-choice variant to watch the max load collapse.
import numpy as np
rng = np.random.default_rng(21)
print(f"{'n':>7} | empty frac (1/e=0.3679) | coll. pairs (theory) | max load")
for n in [100, 1_000, 10_000, 100_000]:
counts = np.bincount(rng.integers(0, n, n), minlength=n) # m = n balls
empty = (counts == 0).mean()
pairs = (counts * (counts - 1) // 2).sum() # sum of C(load, 2)
print(f"{n:>7} | {empty:.4f} | "
f"{pairs:>6} ({(n - 1) / 2:>8.1f}) | {counts.max()}")
# Power of two choices: place each ball in the emptier of two random bins.
n = 100_000
counts = np.zeros(n, dtype=int)
a, b = rng.integers(0, n, n), rng.integers(0, n, n)
for i in range(n):
j = a[i] if counts[a[i]] <= counts[b[i]] else b[i]
counts[j] += 1
print(f"two-choice max load at n={n}: {counts.max()} "
f"(theory ~ lnln n/ln 2 = {np.log(np.log(n)) / np.log(2):.1f}; "
f"one-choice gave 8)")Representative output: empty fractions 0.3600, 0.3660, 0.3652, 0.3678 marching to ; colliding pairs within a few percent of ; one-choice max loads 4, 5, 6, 8 against a two-choice max load of 4 even at .
Practice problems#
Five problems that test whether the occupancy picture is actually installed — each is a balls-into-bins question in disguise, and each yields to indicators, the exponential approximation, or Poissonisation.
How many people are needed for a 50% chance that two share a birth week (52 equally likely weeks)?
Solution. The scaling law answers first: , so guess 9. Exactly: , which is at (collision 43.2%) and at (collision 52.0%). Answer: 9 people. Note the ratio to the day version: — shrinking the bins sevenfold shrinks the threshold by , exactly the law. If you remember one thing, remember that collisions scale with the square root of the bin count.
In a group of 50 people (365 uniform days), what is the expected number of calendar days that are the birthday of exactly two people?
Solution. Indicator per bin: day has exactly two birthdays with probability , so the expectation is days. Poissonisation gets the same number faster: each day’s count is approximately with , so the answer is — within 1.5% of exact. Meanwhile the same group has singleton days and empty days. Lesson: for “how many bins have load ” questions, linearity plus the Poisson profile is the whole method.
Roll a fair die until every face has appeared at least once. Compute the expected number of rolls exactly.
Solution. Coupon collector with bins. Stage decomposition: with faces seen, the wait for a new face is geometric with success probability , mean . Sum:
The stage breakdown is the insight: the first three new faces cost rolls, the last face alone costs 6. Against the continuous approximation — close even at . Lesson: expectations decompose over stages even though the stages are dependent in every other respect; linearity does not care.
Throw balls into bins. What is the probability that bin 1 stays empty? Are the events “bin 1 empty” and “bin 2 empty” independent?
Solution. Each ball misses bin 1 with probability independently, so . For the pair: , while independence would demand . Since , the joint probability is strictly smaller: the events are negatively correlated — balls that spare bin 1 are recycled toward bin 2. But the gap is in the exponent, vanishing for large : asymptotically the bins decouple — the Poissonisation heuristic seen from below. Lesson: bins are never independent, only almost independent, and knowing the size of “almost” is what separates using the heuristic from being used by it.
You must hash keys with probability less than 1% that any two collide. How large must the hash space be? Does a 64-bit hash suffice?
Solution. Collision probability requires , i.e. . So 46 bits of hash are needed for a million keys at the 1% level — the quadratic pair count means the hash space must scale with the square of the key count. A 64-bit hash gives — comfortable; a 32-bit hash gives expected collisions — a certainty of silent data corruption. Lesson: for collision safety, budget bits at plus a safety margin, never — the birthday attack arithmetic, now working for you.
Next: the occupancy model rewards careful conditioning — and the next chapter is a gallery of problems where careless conditioning produces confident, wrong answers: Simpson reversals, the two envelopes, and friends. Probability paradoxes.

