The Birthday Paradox
How many people must be in a room before two of them probably share a birthday? Most people guess somewhere near 180, half of 365. The answer is 23. The surprise is not about birthdays: it is about pairs. With people there are pairs, which grows like , so collisions arrive after about draws from values, not after . That fact sizes hash tables, sets the length of cryptographic hashes and explains why random identifiers collide sooner than expected.
This lesson does the analysis twice, as computer scientists usually do: once exactly, and once with indicator variables, which gives a cruder answer with much less work. Hashing and the Birthday Bound covers the hashing side in more detail.
The model
Each of people has a birthday drawn independently and uniformly from days (; ignore leap years and the real, slightly uneven distribution of births, which only makes collisions more likely). The question: what is the probability that at least two of them share a day?
The exact probability
It is easier to compute the complement, that all birthdays are distinct. Go through the people one by one. The first can have any day; the second must avoid one day, probability ; the third must avoid two, probability ; and so on:
def p_shared(k, n=365):
# probability that some two of k people share a birthday (n equally likely days)
p_distinct = 1.0
for i in range(k):
p_distinct *= (n - i) / n
return 1 - p_distinct
for k in [5, 10, 20, 22, 23, 30, 40, 50, 60, 70]:
print(f"k = {k:2}: Pr[shared birthday] = {p_shared(k):.4f}")
k = next(k for k in range(1, 366) if p_shared(k) > 0.5)
print("smallest k with probability above 1/2:", k)k = 5: Pr[shared birthday] = 0.0271
k = 10: Pr[shared birthday] = 0.1169
k = 20: Pr[shared birthday] = 0.4114
k = 22: Pr[shared birthday] = 0.4757
k = 23: Pr[shared birthday] = 0.5073
k = 30: Pr[shared birthday] = 0.7063
k = 40: Pr[shared birthday] = 0.8912
k = 50: Pr[shared birthday] = 0.9704
k = 60: Pr[shared birthday] = 0.9941
k = 70: Pr[shared birthday] = 0.9992
smallest k with probability above 1/2: 23
With 23 people the probability passes one half; with 70 a shared birthday is almost certain. A seeded simulation agrees.
import random
rng = random.Random(7)
trials = 20000
hits = sum(1 for _ in range(trials)
if len({rng.randrange(365) for _ in range(23)}) < 23)
print(f"23 people, {trials} rooms: shared birthday in {hits / trials:.4f} of them")23 people, 20000 rooms: shared birthday in 0.5110 of them
A clean bound from
The product is exact but does not show the behaviour. The inequality , true for every real , turns it into a sum. With :
So a collision has probability at least , and this is at least as soon as , that is, for . For that is again, and in general about . The bound is also a good approximation while is small compared with , because for small .
The indicator-variable shortcut
Now a different question, which needs far less algebra: what is the expected number of pairs that share a birthday? For each pair of people let
since whatever day person has, person matches it with probability . By linearity of expectation (Indicator Random Variables) over the pairs,
This is at least 1 once , roughly : for , at . Note what this does and does not say. An expected count of at least one pair does not by itself mean that a collision has probability at least one half (the count could be large in a few rooms and zero in the rest). But it gives the right order of growth, , in two lines. Note too that the pair indicators are not independent (if matches and matches , then matches ), and linearity does not care.
from math import exp, log, sqrt
n = 365
print(" k exact Pr[all distinct] bound exp(-k(k-1)/2n) expected pairs")
for k in [10, 20, 23, 28, 40]:
exact = 1.0
for i in range(k):
exact *= 1 - i / n
bound = exp(-k * (k - 1) / (2 * n))
pairs = k * (k - 1) / (2 * n)
print(f"{k:2} {exact:21.4f} {bound:21.4f} {pairs:14.3f}")
k_pairs = next(k for k in range(1, 400) if k * (k - 1) >= 2 * n)
k_bound = next(k for k in range(1, 400) if exp(-k * (k - 1) / (2 * n)) <= 0.5)
print("first k with at least one expected pair:", k_pairs, f"(sqrt(2n) + 1 = {sqrt(2 * n) + 1:.1f})")
print("first k where the bound guarantees Pr[collision] >= 1/2:", k_bound, f"(about sqrt(2 n ln 2) = {sqrt(2 * n * log(2)):.1f})") k exact Pr[all distinct] bound exp(-k(k-1)/2n) expected pairs
10 0.8831 0.8840 0.123
20 0.5886 0.5942 0.521
23 0.4927 0.5000 0.693
28 0.3455 0.3550 1.036
40 0.1088 0.1180 2.137
first k with at least one expected pair: 28 (sqrt(2n) + 1 = 28.0)
first k where the bound guarantees Pr[collision] >= 1/2: 23 (about sqrt(2 n ln 2) = 22.5)
The bound column is always a little above the exact one, as an upper bound must be. At the bound is , which is just below (it prints as 0.5000 after rounding).
Hashing and the square-root rule
Replace "days" with the possible outputs of a hash function and "people" with keys. If the hash behaves like a uniformly random function, the analysis carries over unchanged:
- The first collision is expected after about keys. For a 16-bit hash () that is about 321 keys, not 32,768.
- Among keys the expected number of colliding pairs is . With 100,000 keys and a 32-bit hash it is already above 1.
- A cryptographic hash with -bit output resists random collision search only up to about tries. A 128-bit hash therefore gives only about work against collisions, which is considered too little today; 256-bit hashes are the standard.
import random
from math import pi, sqrt
def first_repeat(rng, n):
seen = set()
while True:
h = rng.randrange(n) # a "hash value" among n possible ones
if h in seen:
return len(seen) + 1 # number of keys hashed when the first collision happened
seen.add(h)
n = 2 ** 16
expected = 0.0 # E[T] = sum over k >= 0 of Pr[first k values distinct]
p = 1.0
for k in range(n + 1):
expected += p
p *= (n - k) / n
rng = random.Random(7)
trials = 2000
avg = sum(first_repeat(rng, n) for _ in range(trials)) / trials
print(f"{n} hash values: first collision after {avg:.1f} keys on average (simulated)")
print(f"exact expectation {expected:.1f}, sqrt(pi n / 2) = {sqrt(pi * n / 2):.1f}")
keys = 100_000
print(f"expected colliding pairs among {keys} keys with 32-bit hashes: {keys * (keys - 1) / 2 / 2 ** 32:.3f}")65536 hash values: first collision after 322.3 keys on average (simulated)
exact expectation 321.5, sqrt(pi n / 2) = 320.8
expected colliding pairs among 100000 keys with 32-bit hashes: 1.164
The exact expectation uses a standard identity: for a random variable taking values , , and "" means "the first values are distinct", the same product as before.
In practice: the square-root rule tells you how big an identifier must be. Random 64-bit IDs collide with probability about one half after roughly , about five billion, IDs; random 122-bit UUIDs need about , which is why nobody checks them for duplicates.
Test yourself
Among people with birthdays uniform over days, what is the expected number of pairs sharing a birthday?
Roughly how many random values from possibilities are needed before a repeat becomes likely?
Which inequality turns the exact product into the bound ?
- for all real
- Markov's inequality
A hash function has 32-bit outputs. About how many random keys give a collision with probability one half?
- About 77 thousand ()
- About 2 billion ()
- About 32
- About 4 billion ()