TExcelTAD
Home › Discrete Mathematics › Hashing and the Birthday Bound

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 m+1m + 1 items in mm slots; the birthday bound says they become likely after only about m\sqrt{m}.

The exact probability

Throw nn items independently and uniformly into mm slots. The probability that all land in different slots is

Pr⁡[no collision]=mm⋅m−1m⋯m−n+1m=∏i=0n−1(1−im)\Pr[\text{no collision}] = \frac{m}{m} \cdot \frac{m-1}{m} \cdots \frac{m-n+1}{m} = \prod_{i=0}^{n-1} \left(1 - \frac{i}{m}\right)

using the generalized product rule: the (i+1)(i+1)-th item must avoid the ii slots already taken.

The approximation

Since 1−x≤e−x1 - x \le e^{-x} (and is close to it for small xx),

Pr⁡[no collision]≈∏i=0n−1e−i/m=e−n(n−1)/(2m)≈e−n2/(2m)\Pr[\text{no collision}] \approx \prod_{i=0}^{n-1} e^{-i/m} = e^{-n(n-1)/(2m)} \approx e^{-n^2/(2m)}

So collisions become likely once n2≈2mln⁡2n^2 \approx 2m \ln 2, that is around n≈1.18mn \approx 1.18\sqrt{m}. For m=365m = 365 this gives 22.5.

python · try it yourself
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, (n2)≈n22\binom{n}{2} \approx \frac{n^2}{2}, and each pair collides with probability 1m\frac{1}{m}. By linearity of expectation, the expected number of colliding pairs is (n2)/m\binom{n}{2}/m, which reaches 1 at n≈2mn \approx \sqrt{2m}.

What it means for hash sizes

Hash / ID size Slots mm Items for a 50% collision chance
32 bits 232≈4.3×1092^{32} \approx 4.3 \times 10^9 about 77,000
64 bits 2642^{64} about 5 billion
128 bits (UUID v4 has 122 random bits) 21222^{122} about 2.7×10182.7 \times 10^{18}
256 bits (SHA-256) 22562^{256} about 4×10384 \times 10^{38}

So 32-bit random IDs are unsafe for even a modest database, and a cryptographic hash with bb-bit output offers only about b/2b/2 bits of collision resistance: finding some pair of colliding inputs takes about 2b/22^{b/2} tries (the birthday attack), far fewer than 2b2^b. This is why MD5 (128 bits) and SHA-1 (160 bits) were retired for signatures and why SHA-256 is the minimum today.

python · try it yourself
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 (m≈1.7×107m \approx 1.7 \times 10^7) and hash distinct messages until two collide. The bound predicts about 1.18⋅212≈48001.18 \cdot 2^{12} \approx 4800 tries, not millions:

python · try it yourself
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 += 1
collision 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 O(1)O(1) 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

1−e−40⋅39/730=1−e−2.137≈1−0.118=0.8821 - e^{-40 \cdot 39 / 730} = 1 - e^{-2.137} \approx 1 - 0.118 = 0.882. (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

m=626≈5.68×1010m = 62^6 \approx 5.68 \times 10^{10}, and 1.18m≈1.18⋅238,000≈281,0001.18\sqrt{m} \approx 1.18 \cdot 238{,}000 \approx 281{,}000. 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, (10002)/105\binom{1000}{2} / 10^5, with a simulation.

Answer

About 5 colliding pairs expected; simulations average close to 5.

Solution

(10002)=499500\binom{1000}{2} = 499500, divided by 10510^5 gives 4.995.

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

  1. About 77,000
  2. About 2 billion
  3. About 4 billion
  4. About 65,000,000

A bb-bit cryptographic hash offers roughly how many bits of collision resistance?

  1. bb
  2. b/2b/2
  3. 2b2b
  4. log⁡2b\log_2 b

The birthday bound grows like the square root of the number of slots because collisions depend on…

  1. the number of items
  2. the number of pairs of items
  3. the hash function's speed
  4. the order of insertion