Hashing and the Birthday Bound
In a room of 23 people, the chance that two share a birthday is over 50%. This birthday paradox is not a curiosity: it decides how big hash values, random IDs and cryptographic digests must be. The pigeonhole principle says collisions are certain after items in slots; the birthday bound says they become likely after only about .
The exact probability
Throw items independently and uniformly into slots. The probability that all land in different slots is
using the generalized product rule: the -th item must avoid the slots already taken.
The approximation
Since (and is close to it for small ),
So collisions become likely once , that is around . For this gives 22.5.
import math
def p_collision(n, m):
p = 1.0
for i in range(n):
p *= 1 - i / m
return 1 - p
for n in [10, 20, 23, 30, 50, 70]:
approx = 1 - math.exp(-n * (n - 1) / (2 * 365))
print(f"n={n:2d}: exact={p_collision(n, 365):.4f} approx={approx:.4f}")
print("people needed for 50%:", next(n for n in range(1, 100) if p_collision(n, 365) >= 0.5))n=10: exact=0.1169 approx=0.1160
n=20: exact=0.4114 approx=0.4058
n=23: exact=0.5073 approx=0.5000
n=30: exact=0.7063 approx=0.6963
n=50: exact=0.9704 approx=0.9651
n=70: exact=0.9992 approx=0.9987
people needed for 50%: 23
The intuition: what matters is the number of pairs, , and each pair collides with probability . By linearity of expectation, the expected number of colliding pairs is , which reaches 1 at .
What it means for hash sizes
| Hash / ID size | Slots | Items for a 50% collision chance |
|---|---|---|
| 32 bits | about 77,000 | |
| 64 bits | about 5 billion | |
| 128 bits (UUID v4 has 122 random bits) | about | |
| 256 bits (SHA-256) | about |
So 32-bit random IDs are unsafe for even a modest database, and a cryptographic hash with -bit output offers only about bits of collision resistance: finding some pair of colliding inputs takes about tries (the birthday attack), far fewer than . This is why MD5 (128 bits) and SHA-1 (160 bits) were retired for signatures and why SHA-256 is the minimum today.
import math
def items_for_half(bits):
m = 2.0 ** bits
return math.sqrt(2 * m * math.log(2))
for bits in [16, 32, 64, 128, 256]:
print(f"{bits:3d}-bit hash: ~{items_for_half(bits):.3g} items for a 50% collision chance") 16-bit hash: ~301 items for a 50% collision chance
32-bit hash: ~7.72e+04 items for a 50% collision chance
64-bit hash: ~5.06e+09 items for a 50% collision chance
128-bit hash: ~2.17e+19 items for a 50% collision chance
256-bit hash: ~4.01e+38 items for a 50% collision chance
A birthday attack in miniature
Truncate SHA-256 to 24 bits () and hash distinct messages until two collide. The bound predicts about tries, not millions:
import hashlib
def h24(msg):
return hashlib.sha256(msg.encode()).digest()[:3]
seen = {}
i = 0
while True:
msg = f"message-{i}"
d = h24(msg)
if d in seen:
print(f"collision after {i + 1} messages: {seen[d]!r} and {msg!r} -> {d.hex()}")
break
seen[d] = msg
i += 1collision after 2699 messages: 'message-42' and 'message-2698' -> a0f23d
In software
Hash tables expect collisions and resolve them by chaining or probing; their expected cost stays when the load factor is bounded. Git's object IDs moved from SHA-1 toward SHA-256 partly because of practical SHA-1 collisions. Distributed systems pick random IDs of at least 122 bits (UUID v4) or use coordinated IDs (Snowflake) precisely because of the birthday bound. Bloom filters and HyperLogLog are designed with this same collision arithmetic.
Exercises
Exercise 1: Class birthdays
In a class of 40, estimate the probability that two share a birthday using the approximation.
Answer
About 0.88.
Solution
. (The exact value is 0.891.)
Exercise 2: Short URLs
A URL shortener uses random 6-character codes over 62 symbols. After about how many links is a collision likely?
Answer
About 280,000.
Solution
, and . Real shorteners check for existing codes or use counters.
Exercise 3: Expected collisions (code)
Insert 1000 random keys into a table of 100,000 slots. Compare the expected number of colliding pairs, , with a simulation.
Answer
About 5 colliding pairs expected; simulations average close to 5.
Solution
, divided by gives 4.995.
import random
from collections import Counter
rng = random.Random(10)
runs, total = 200, 0
for _ in range(runs):
c = Counter(rng.randrange(100000) for _ in range(1000))
total += sum(k * (k - 1) // 2 for k in c.values())
print(round(total / runs, 2), 1000 * 999 / 2 / 100000)5.11 4.995
Test yourself
About how many random 32-bit IDs give a 50% chance of a duplicate?
- About 77,000
- About 2 billion
- About 4 billion
- About 65,000,000
A -bit cryptographic hash offers roughly how many bits of collision resistance?
The birthday bound grows like the square root of the number of slots because collisions depend on…
- the number of items
- the number of pairs of items
- the hash function's speed
- the order of insertion