Sub topic 4
Collisions Are Unavoidable
This chapter assumes you can read Python, understand that a hash function maps input to a fixed-size value, and are comfortable with powers of two and the modulo operator. You should also know what a hash table is, at the level of "a dictionary backed by an array of buckets".
By the end you will be able to explain why every hash function has collisions, count how many inputs must share an output, and separate "a collision exists" from "someone can find one".
What a collision is
A collision is a pair of different inputs x and y with hash(x) == hash(y). Hash functions are deterministic, so the same input always gives the same output. Collisions are about different inputs that share an output.
Collisions are not a sign of a buggy hash. A perfect hash function still has them. The reason is arithmetic.
The pigeonhole principle
The pigeonhole principle says that if you put more than m items into m boxes, at least one box holds two or more items. A stronger form says that with n items in m boxes, some box holds at least ceil(n / m) items.
A hash function with a k-bit output has 2^k possible outputs, which are the boxes. The inputs are the items. If there are more possible inputs than outputs, some output must be shared.
Most hash functions accept inputs of any length, so the number of possible inputs is unbounded. Even if you cap the length, the input space grows much faster than the output space.
| Hash | Output size | Possible outputs | Possible 300-bit inputs |
|---|---|---|---|
| 32-bit FNV-1a | 32 bits | about 4.3 billion | 2^300 |
| 64-bit hash | 64 bits | about 1.8 × 10^19 | 2^300 |
| SHA-256 | 256 bits | 2^256 | 2^300 |
Even SHA-256 has more possible 300-bit inputs than outputs. On average, each SHA-256 output is shared by 2^44 different 300-bit messages. Those messages exist. Nobody has found two of them.
Seeing the principle in code
The next program hashes 1000 keys into 16 buckets. Since 1000 / 16 = 62.5, the principle guarantees that at least one bucket holds 63 or more keys. The assert checks that guarantee.
import math
from collections import Counter
def bucket_of(key: str, buckets: int) -> int:
h = 0
for b in key.encode():
h = (h * 31 + b) % (2**32)
return h % buckets
keys = [f"user-{i}" for i in range(1000)]
buckets = 16
loads = Counter(bucket_of(k, buckets) for k in keys)
print("fullest bucket:", max(loads.values()))
print("guaranteed minimum:", math.ceil(len(keys) / buckets))
assert max(loads.values()) >= math.ceil(len(keys) / buckets)The assertion cannot fail, whatever hash function you substitute. A better hash only makes the loads closer to the minimum of 63. It cannot push the maximum below it.
Collisions happen early
The pigeonhole principle sets the point at which a collision is certain. A collision usually appears much sooner. With m possible outputs, a collision is likely after roughly the square root of m random inputs, which is the birthday effect. A later chapter works out the numbers.
You can watch this with a deliberately short hash. The program below truncates SHA-256 to 16 bits, which gives 65,536 outputs. The pigeonhole principle guarantees a collision within 65,537 inputs. In practice the search ends after a few hundred.
import hashlib
def tiny_hash(data: bytes, bits: int = 16) -> int:
digest = hashlib.sha256(data).digest()
return int.from_bytes(digest, "big") >> (256 - bits)
def find_collision(bits: int = 16):
seen = {}
i = 0
while True:
msg = f"message-{i}".encode()
h = tiny_hash(msg, bits)
if h in seen:
return seen[h], msg, h, i + 1
seen[h] = msg
i += 1
first, second, value, tries = find_collision()
print(first, second, "both hash to", value)
print("found after", tries, "messages")
assert first != second
assert tiny_hash(first) == tiny_hash(second)The search stores every hash it has seen in a dictionary. This is why it is fast: each new message is compared against all earlier ones with a single lookup. Try bits=24 and bits=32. Each extra 8 bits makes the search about 16 times longer, because the work grows with the square root of the output space. Real hashes follow the same rule, only with far larger numbers.
Exists versus findable
Beginners often mix up two claims.
- A collision exists. This is always true when inputs outnumber outputs, and the pigeonhole principle proves it.
- A collision can be found. This depends on the hash function and on how much computation the attacker has.
For a 16-bit hash, both claims hold within a fraction of a second. For SHA-256, claim 1 holds and claim 2 is believed to be false, because a birthday search would need about 2^128 hash evaluations. That number is far beyond any real computing capacity.
The rest of this tutorial depends on this split. Hash tables only need collisions to be rare and handled correctly. Cryptographic hashes need them to be infeasible to find on purpose.
Collisions you can see in everyday code
Real collisions are not limited to truncated demos. CPython computes the hash of an integer as the integer itself, except that -1 is reserved as an error signal in the C API. As a result, -1 and -2 collide.
print(hash(-1), hash(-2))
print(hash(-1) == hash(-2))
print(-1 == -2)
table = {-1: "minus one", -2: "minus two"}
print(table[-1], table[-2])The first print shows both values as -2. The comparison -1 == -2 is False, and the dictionary still returns the right value for each key. The dictionary does not trust the hash alone. It first uses the hash to find a candidate slot, then compares keys with ==.
Handling collisions
Since collisions cannot be avoided, a hash table must cope with them. The two common strategies are:
- Chaining: each bucket holds a list, and colliding keys are appended to it. A lookup hashes the key, goes to the bucket, and scans the list using
==. - Open addressing: each slot holds at most one entry. If the target slot is taken, the table probes other slots by a fixed rule until it finds a free one or the key.
Both strategies slow down as collisions pile up. With a good hash and a table that is not too full, buckets hold about one entry and operations take constant time on average. With a bad hash, many keys land in one bucket, and lookups degrade toward scanning a list.
Common errors
- Treating equal hashes as equal values. Equal hashes mean the inputs might be equal. Only a direct comparison confirms it. A table that skipped the comparison would return wrong data for colliding keys.
- Treating different hashes as a proof of anything else. Different hashes do prove that the inputs differ, because a deterministic function cannot give two outputs for the same input. This one-way inference is the basis of fast "has it changed?" checks.
- Using a short hash as a unique identifier. A 32-bit hash as an ID will collide in a large dataset. A system that assumes IDs are unique will silently merge or overwrite records.
- Believing a longer output removes collisions. It only makes them harder to find. The pigeonhole count is unchanged.
Summary of the argument
- A hash function maps an unbounded (or just very large) input space to a fixed set of
2^koutputs. - By the pigeonhole principle, some outputs must be shared by more than one input.
- Collisions therefore always exist. The design question is how often they occur for realistic inputs, and how hard they are to find on purpose.
- Table implementations handle them by comparing keys. Security uses rely on making them infeasible to find.
Exercise
A hash function produces 8-bit outputs. You hash 1,000 distinct strings. What is the smallest number of strings that must share one output value, and why? Would switching to a better 8-bit hash lower this number?
Show answer
There are 2^8 = 256 possible outputs. By the pigeonhole principle, some output is shared by at least ceil(1000 / 256) = 4 strings. A better 8-bit hash cannot lower this guaranteed minimum, because the bound depends only on the number of inputs and outputs. A better hash only makes the actual loads closer to that minimum, instead of letting some buckets receive many more strings.
Exercise
In the find_collision program, the search is guaranteed to stop after at most 65,537 messages when bits=16. Explain why, and say what the guaranteed limit would be for bits=20.
Show answer
With 16 bits there are 65,536 possible hash values. After 65,536 distinct messages, every value could have been used once. The 65,537th message must repeat a value, so the dictionary lookup succeeds by then. For bits=20 there are 2^20 = 1,048,576 values, so the guaranteed limit is 1,048,577 messages. The expected number of messages needed is much smaller, on the order of a thousand.