TExcelTAD
Home › Foundations of Algorithm Analysis › The Birthday Paradox

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 kk people there are (k2)\binom{k}{2} pairs, which grows like k2k^2, so collisions arrive after about n\sqrt{n} draws from nn values, not after n/2n/2. 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 kk people has a birthday drawn independently and uniformly from nn days (n=365n = 365; 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 kk birthdays are distinct. Go through the people one by one. The first can have any day; the second must avoid one day, probability n−1n\frac{n-1}{n}; the third must avoid two, probability n−2n\frac{n-2}{n}; and so on:

Pr⁡[all distinct]=∏i=0k−1n−in=∏i=1k−1(1−in)\Pr[\text{all distinct}] = \prod_{i=0}^{k-1} \frac{n-i}{n} = \prod_{i=1}^{k-1} \left(1 - \frac{i}{n}\right)
python · try it yourself
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.

python · try it yourself
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 1+x≤ex1 + x \le e^x

The product is exact but does not show the n\sqrt{n} behaviour. The inequality 1+x≤ex1 + x \le e^x, true for every real xx, turns it into a sum. With x=−i/nx = -i/n:

Pr⁡[all distinct]=∏i=1k−1(1−in)≤∏i=1k−1e−i/n=exp⁡(−1n∑i=1k−1i)=exp⁡(−k(k−1)2n)\begin{aligned} \Pr[\text{all distinct}] &= \prod_{i=1}^{k-1} \left(1 - \frac{i}{n}\right) \le \prod_{i=1}^{k-1} e^{-i/n} \\ &= \exp\left(-\frac{1}{n}\sum_{i=1}^{k-1} i\right) = \exp\left(-\frac{k(k-1)}{2n}\right) \end{aligned}

So a collision has probability at least 1−e−k(k−1)/(2n)1 - e^{-k(k-1)/(2n)}, and this is at least 12\frac{1}{2} as soon as k(k−1)≥2nln⁡2k(k-1) \ge 2n \ln 2, that is, for k≥12(1+1+8nln⁡2)k \ge \frac{1}{2}\left(1 + \sqrt{1 + 8n\ln 2}\right). For n=365n = 365 that is k=23k = 23 again, and in general about 2nln⁡2≈1.18n\sqrt{2n \ln 2} \approx 1.18\sqrt{n}. The bound is also a good approximation while kk is small compared with nn, because 1−x≈e−x1 - x \approx e^{-x} for small xx.

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 i<ji < j let

Xij=I{persons i and j share a birthday},Pr⁡[Xij=1]=1nX_{ij} = I\{\text{persons } i \text{ and } j \text{ share a birthday}\}, \qquad \Pr[X_{ij} = 1] = \frac{1}{n}

since whatever day person ii has, person jj matches it with probability 1n\frac{1}{n}. By linearity of expectation (Indicator Random Variables) over the (k2)\binom{k}{2} pairs,

E[∑i<jXij]=(k2)⋅1n=k(k−1)2n\mathbb{E}\left[\sum_{i<j} X_{ij}\right] = \binom{k}{2} \cdot \frac{1}{n} = \frac{k(k-1)}{2n}

This is at least 1 once k(k−1)≥2nk(k-1) \ge 2n, roughly k≥2n+1k \ge \sqrt{2n} + 1: for n=365n = 365, at k=28k = 28. 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, Θ(n)\Theta(\sqrt{n}), in two lines. Note too that the pair indicators are not independent (if ii matches jj and jj matches ll, then ii matches ll), and linearity does not care.

python · try it yourself
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 k=23k = 23 the bound is e−506/730e^{-506/730}, which is just below 12\frac{1}{2} (it prints as 0.5000 after rounding).

Hashing and the square-root rule

Replace "days" with the nn 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 πn/2\sqrt{\pi n / 2} keys. For a 16-bit hash (n=65536n = 65536) that is about 321 keys, not 32,768.
  • Among kk keys the expected number of colliding pairs is k(k−1)2n\frac{k(k-1)}{2n}. With 100,000 keys and a 32-bit hash it is already above 1.
  • A cryptographic hash with bb-bit output resists random collision search only up to about 2b/22^{b/2} tries. A 128-bit hash therefore gives only about 2642^{64} work against collisions, which is considered too little today; 256-bit hashes are the standard.
python · try it yourself
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 TT taking values 1,2,…1, 2, \ldots, E[T]=∑k≥0Pr⁡[T>k]\mathbb{E}[T] = \sum_{k \ge 0} \Pr[T > k], and "T>kT > k" means "the first kk 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 1.18⋅2321.18 \cdot 2^{32}, about five billion, IDs; random 122-bit UUIDs need about 2612^{61}, which is why nobody checks them for duplicates.

Test yourself

Among kk people with birthdays uniform over nn days, what is the expected number of pairs sharing a birthday?

  1. kn\frac{k}{n}
  2. k(k−1)2n\frac{k(k-1)}{2n}
  3. k2n2\frac{k^2}{n^2}
  4. 1−e−k/n1 - e^{-k/n}

Roughly how many random values from nn possibilities are needed before a repeat becomes likely?

  1. Θ(log⁡n)\Theta(\log n)
  2. Θ(n)\Theta(\sqrt{n})
  3. n/2n/2
  4. Θ(n)\Theta(n)

Which inequality turns the exact product ∏i=1k−1(1−i/n)\prod_{i=1}^{k-1}(1 - i/n) into the bound e−k(k−1)/(2n)e^{-k(k-1)/(2n)}?

  1. 1+x≤ex1 + x \le e^x for all real xx
  2. Markov's inequality
  3. (k2)≤k2\binom{k}{2} \le k^2
  4. ex≤1+2xe^x \le 1 + 2x

A hash function has 32-bit outputs. About how many random keys give a collision with probability one half?

  1. About 77 thousand (1.18⋅2161.18 \cdot 2^{16})
  2. About 2 billion (2312^{31})
  3. About 32
  4. About 4 billion (2322^{32})