{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"hashing-and-the-birthday-bound","title":"Hashing, collisions, and the square-root law behind them","url":"https://addaly.com/learn/maths-you-need/hashing-and-the-birthday-bound","position":63,"of":76,"minutes":9,"answer":"Hashing gives constant-time lookup by scattering inputs evenly, and the birthday bound says a repeat is likely after only √(2m) draws from m values, which is why a 32-bit key collides by 77.","keyIdea":"Hashing gives constant-time lookup by scattering inputs evenly, and the birthday bound says a repeat is likely after only √(2m) draws from m values, which is why a 32-bit key collides by 77,000 items and why Bloom filters, the hashing trick and locality-sensitive deduplication can each be sized from one formula."},"body":{"format":"markdown","text":"## Turning anything into a number\n\nA hash function takes an input of any size and returns a fixed-size number, in a way that scatters inputs evenly across the possible outputs and makes similar inputs land far apart. Change one character of a document and its 64-bit hash changes in about half its bits. That property, plus speed, is why hashing sits under half the data structures in a machine-learning pipeline.\n\nThe hash table is the first. Store an item in the bucket its hash points to; to check membership, hash the query and look in that one bucket. The lookup does not depend on how many items are stored. That is the `O(1)` from the Big-O lesson, and it is why `item in some_set` is a thousand times faster than `item in some_list` at a million items: the set hashes, the list scans.\n\n## Collisions are a counting problem\n\nTwo different inputs can hash to the same value. With `n` items and `m` possible hash values, the number of pairs is about `n²/2` and each pair collides with probability `1/m`, so\n\n```\nexpected collisions ≈ n² / 2m\nP(at least one)     ≈ 1 − exp(−n² / 2m)\n```\n\nCollisions become likely when `n²/2m` approaches 1, that is when `n ≈ √(2m)`. This is the **birthday bound**: you need only the square root of the number of possible values before two items share one. In a room of 23 people, with 365 possible birthdays, the chance of a shared one is 50 per cent, and `1.18 × √365 = 22.5`.\n\nApply it to hash sizes:\n\n```\n32-bit hash, m = 4.3 × 10^9:   collision likely by n ≈ 77,000 items\n64-bit hash, m = 1.8 × 10^19:  collision likely by n ≈ 5 × 10^9 items\n128-bit:                        n ≈ 2 × 10^19\n```\n\nA million documents keyed by a 32-bit hash will certainly collide: `n²/2m = 116`, so `1 − e^(−116)` is 1 to every decimal place. The same million under a 64-bit hash collide with probability `2.7 × 10^-8`. If a deduplication or caching system uses a 32-bit key, it is silently merging unrelated records somewhere past the first hundred thousand. This is a real and common bug, and the arithmetic above finds it before the data does.\n\n## The hashing trick\n\nWhen a vocabulary is enormous, every distinct URL, user id or n-gram, you can skip building a dictionary and hash each feature directly to one of `2^20` positions in a vector. Collisions are tolerated: two features sharing a slot add their values, which acts as a small amount of noise. How much? With a million features in a million slots, the count per slot is Poisson with mean 1: 37 per cent of slots are empty, 37 per cent hold one feature, 26 per cent hold two or more. A quarter of the features share a slot with something. If that is too much, use `2^24` slots and the sharing falls to about 6 per cent; the arithmetic tells you the trade before you train.\n\n## Bloom filters: membership in a tenth of the space\n\nTo remember which of a billion URLs you have already fetched, a set of the URLs themselves is tens of gigabytes. A Bloom filter keeps a bit array of `m` bits and `k` hash functions; to add an item, set the `k` bits it hashes to; to query, check whether all `k` are set. It never says \"absent\" wrongly, but it can say \"present\" wrongly, with probability\n\n```\nP(false positive) ≈ (1 − e^(−kn/m))^k\n```\n\nAt ten bits per item and `k = 7`, that is `(1 − e^(−0.7))^7 = 0.8` per cent. A billion URLs in 1.25 GB, with under one wrong answer in a hundred, and no way to list what is in it. The formula lets you buy exactly the error rate you can afford.\n\n## Locality-sensitive hashing: collisions on purpose\n\nOrdinary hashing scatters similar inputs apart. For deduplication and nearest-neighbour search you want the opposite: similar inputs *should* collide. Locality-sensitive schemes are built so that the probability two items share a hash equals, or tracks, their similarity. The MinHash signature of a document, for instance, collides with another's with probability equal to the Jaccard overlap of their word sets. Bucket by a few signature bands and only compare within buckets, and the all-pairs deduplication from two lessons ago becomes near-linear. The pairs that never shared a bucket were, with high probability, never near-duplicates.\n\n## The reproducibility trap\n\nPython randomises its string hashing per process, so that adversarial inputs cannot force collisions. A consequence: the iteration order of a set of strings differs between runs. A pipeline that builds a vocabulary by iterating a set will assign different ids on Tuesday than on Monday, and a model trained on one will read garbage from the other. Set `PYTHONHASHSEED=0` for reproducible runs, or, better, sort before assigning ids. The lesson on random numbers in module 8 has the rest of that story.\n\n## In code\n\n```python\nimport hashlib, math\nh = int(hashlib.blake2b(b\"some document\", digest_size=8).hexdigest(), 16)  # 64-bit\nn, m = 1_000_000, 2**32\nprint(1 - math.exp(-n*n / (2*m)))     # 1.0: a 32-bit key will collide\n```\n\nUse a 64-bit or 128-bit digest for anything you key on, size the Bloom filter from the formula, and read the birthday bound as the general warning it is: whenever something is drawn at random from `m` possibilities, a repeat is due after about `√m` draws, not `m`."},"check":{"question":"A caching layer keys entries by a 32-bit hash of the request. It works in testing and starts returning wrong responses in production at a few hundred thousand distinct requests. What is happening?","options":[{"text":"The cache is evicting entries, so requests are being recomputed with a subtly different result.","correct":false,"tempting":"Eviction causes recomputation, not wrong answers; returning another request's response is the signature of two keys mapping to one slot."},{"text":"The hash function is poorly chosen and clusters similar requests together.","correct":false,"tempting":"Even a perfectly uniform 32-bit hash collides by the birthday bound; the fault is the key size, not the function's quality."},{"text":"Collisions should only appear near 4.3 billion entries, so the cause must be elsewhere.","correct":false,"tempting":"Confuses the number of possible values with the number of draws before a repeat; the latter is the square root, tens of thousands, not billions."},{"text":"Distinct requests collide: a repeat among 4.3 billion values is due by about 77,000 items.","correct":true}]},"prev":{"slug":"arithmetic-intensity-and-the-roofline","title":"Why a GPU idles: memory-bound versus compute-bound","url":"https://addaly.com/learn/maths-you-need/arithmetic-intensity-and-the-roofline"},"next":{"slug":"graphs-as-matrices","title":"A graph is a matrix, and its paths are its powers","url":"https://addaly.com/learn/maths-you-need/graphs-as-matrices"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Hashing, collisions, and the square-root law behind them', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/hashing-and-the-birthday-bound (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Hashing, collisions, and the square-root law behind them","courseTitle":"The Maths You Actually Need","module":{"index":7,"slug":"cost-and-scale","title":"Counting the cost: complexity and the arithmetic of scale"},"answer":null,"keyIdea":"Hashing gives constant-time lookup by scattering inputs evenly, and the birthday bound says a repeat is likely after only √(2m) draws from m values, which is why a 32-bit key collides by 77,000 items and why Bloom filters, the hashing trick and locality-sensitive deduplication can each be sized from one formula.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"turning-anything-into-a-number","runs":[{"text":"Turning anything into a number"}]},{"t":"p","runs":[{"text":"A hash function takes an input of any size and returns a fixed-size number, in a way that scatters inputs evenly across the possible outputs and makes similar inputs land far apart. Change one character of a document and its 64-bit hash changes in about half its bits. That property, plus speed, is why hashing sits under half the data structures in a machine-learning pipeline."}]},{"t":"p","runs":[{"text":"The hash table is the first. Store an item in the bucket its hash points to; to check membership, hash the query and look in that one bucket. The lookup does not depend on how many items are stored. That is the "},{"text":"O(1)","code":true},{"text":" from the Big-O lesson, and it is why "},{"text":"item in some_set","code":true},{"text":" is a thousand times faster than "},{"text":"item in some_list","code":true},{"text":" at a million items: the set hashes, the list scans."}]},{"t":"h2","id":"collisions-are-a-counting-problem","runs":[{"text":"Collisions are a counting problem"}]},{"t":"p","runs":[{"text":"Two different inputs can hash to the same value. With "},{"text":"n","code":true},{"text":" items and "},{"text":"m","code":true},{"text":" possible hash values, the number of pairs is about "},{"text":"n²/2","code":true},{"text":" and each pair collides with probability "},{"text":"1/m","code":true},{"text":", so"}]},{"t":"code","lang":"","label":"Text","text":"expected collisions ≈ n² / 2m\nP(at least one)     ≈ 1 − exp(−n² / 2m)"},{"t":"p","runs":[{"text":"Collisions become likely when "},{"text":"n²/2m","code":true},{"text":" approaches 1, that is when "},{"text":"n ≈ √(2m)","code":true},{"text":". This is the "},{"text":"birthday bound","b":true},{"text":": you need only the square root of the number of possible values before two items share one. In a room of 23 people, with 365 possible birthdays, the chance of a shared one is 50 per cent, and "},{"text":"1.18 × √365 = 22.5","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"Apply it to hash sizes:"}]},{"t":"code","lang":"","label":"Text","text":"32-bit hash, m = 4.3 × 10^9:   collision likely by n ≈ 77,000 items\n64-bit hash, m = 1.8 × 10^19:  collision likely by n ≈ 5 × 10^9 items\n128-bit:                        n ≈ 2 × 10^19"},{"t":"p","runs":[{"text":"A million documents keyed by a 32-bit hash will certainly collide: "},{"text":"n²/2m = 116","code":true},{"text":", so "},{"text":"1 − e^(−116)","code":true},{"text":" is 1 to every decimal place. The same million under a 64-bit hash collide with probability "},{"text":"2.7 × 10^-8","code":true},{"text":". If a deduplication or caching system uses a 32-bit key, it is silently merging unrelated records somewhere past the first hundred thousand. This is a real and common bug, and the arithmetic above finds it before the data does."}]},{"t":"h2","id":"the-hashing-trick","runs":[{"text":"The hashing trick"}]},{"t":"p","runs":[{"text":"When a vocabulary is enormous, every distinct URL, user id or n-gram, you can skip building a dictionary and hash each feature directly to one of "},{"text":"2^20","code":true},{"text":" positions in a vector. Collisions are tolerated: two features sharing a slot add their values, which acts as a small amount of noise. How much? With a million features in a million slots, the count per slot is Poisson with mean 1: 37 per cent of slots are empty, 37 per cent hold one feature, 26 per cent hold two or more. A quarter of the features share a slot with something. If that is too much, use "},{"text":"2^24","code":true},{"text":" slots and the sharing falls to about 6 per cent; the arithmetic tells you the trade before you train."}]},{"t":"h2","id":"bloom-filters-membership-in-a-tenth-of-the-space","runs":[{"text":"Bloom filters: membership in a tenth of the space"}]},{"t":"p","runs":[{"text":"To remember which of a billion URLs you have already fetched, a set of the URLs themselves is tens of gigabytes. A Bloom filter keeps a bit array of "},{"text":"m","code":true},{"text":" bits and "},{"text":"k","code":true},{"text":" hash functions; to add an item, set the "},{"text":"k","code":true},{"text":" bits it hashes to; to query, check whether all "},{"text":"k","code":true},{"text":" are set. It never says “absent” wrongly, but it can say “present” wrongly, with probability"}]},{"t":"code","lang":"","label":"Text","text":"P(false positive) ≈ (1 − e^(−kn/m))^k"},{"t":"p","runs":[{"text":"At ten bits per item and "},{"text":"k = 7","code":true},{"text":", that is "},{"text":"(1 − e^(−0.7))^7 = 0.8","code":true},{"text":" per cent. A billion URLs in 1.25 GB, with under one wrong answer in a hundred, and no way to list what is in it. The formula lets you buy exactly the error rate you can afford."}]},{"t":"h2","id":"locality-sensitive-hashing-collisions-on-purpose","runs":[{"text":"Locality-sensitive hashing: collisions on purpose"}]},{"t":"p","runs":[{"text":"Ordinary hashing scatters similar inputs apart. For deduplication and nearest-neighbour search you want the opposite: similar inputs "},{"text":"should","i":true},{"text":" collide. Locality-sensitive schemes are built so that the probability two items share a hash equals, or tracks, their similarity. The MinHash signature of a document, for instance, collides with another’s with probability equal to the Jaccard overlap of their word sets. Bucket by a few signature bands and only compare within buckets, and the all-pairs deduplication from two lessons ago becomes near-linear. The pairs that never shared a bucket were, with high probability, never near-duplicates."}]},{"t":"h2","id":"the-reproducibility-trap","runs":[{"text":"The reproducibility trap"}]},{"t":"p","runs":[{"text":"Python randomises its string hashing per process, so that adversarial inputs cannot force collisions. A consequence: the iteration order of a set of strings differs between runs. A pipeline that builds a vocabulary by iterating a set will assign different ids on Tuesday than on Monday, and a model trained on one will read garbage from the other. Set "},{"text":"PYTHONHASHSEED=0","code":true},{"text":" for reproducible runs, or, better, sort before assigning ids. The lesson on random numbers in module 8 has the rest of that story."}]},{"t":"h2","id":"in-code","runs":[{"text":"In code"}]},{"t":"code","lang":"python","label":"Python","text":"import hashlib, math\nh = int(hashlib.blake2b(b\"some document\", digest_size=8).hexdigest(), 16)  # 64-bit\nn, m = 1_000_000, 2**32\nprint(1 - math.exp(-n*n / (2*m)))     # 1.0: a 32-bit key will collide"},{"t":"p","runs":[{"text":"Use a 64-bit or 128-bit digest for anything you key on, size the Bloom filter from the formula, and read the birthday bound as the general warning it is: whenever something is drawn at random from "},{"text":"m","code":true},{"text":" possibilities, a repeat is due after about "},{"text":"√m","code":true},{"text":" draws, not "},{"text":"m","code":true},{"text":"."}]}],"check":{"question":[{"text":"A caching layer keys entries by a 32-bit hash of the request. It works in testing and starts returning wrong responses in production at a few hundred thousand distinct requests. What is happening?"}],"options":[{"text":[{"text":"The cache is evicting entries, so requests are being recomputed with a subtly different result."}],"correct":false,"tempting":[{"text":"Eviction causes recomputation, not wrong answers; returning another request’s response is the signature of two keys mapping to one slot."}]},{"text":[{"text":"The hash function is poorly chosen and clusters similar requests together."}],"correct":false,"tempting":[{"text":"Even a perfectly uniform 32-bit hash collides by the birthday bound; the fault is the key size, not the function’s quality."}]},{"text":[{"text":"Collisions should only appear near 4.3 billion entries, so the cause must be elsewhere."}],"correct":false,"tempting":[{"text":"Confuses the number of possible values with the number of draws before a repeat; the latter is the square root, tens of thousands, not billions."}]},{"text":[{"text":"Distinct requests collide: a repeat among 4.3 billion values is due by about 77,000 items."}],"correct":true,"tempting":null}],"order":[2,3,0,1],"why":null},"prev":{"slug":"arithmetic-intensity-and-the-roofline","title":"Why a GPU idles: memory-bound versus compute-bound","minutes":10},"next":{"slug":"graphs-as-matrices","title":"A graph is a matrix, and its paths are its powers","minutes":9}}}