Sub topic 5
Collisions are unavoidable
This chapter assumes you know the modulo operator, indexing arrays by position, and introductory Big-O. It also assumes you have seen the idea of a hash function that turns a key into an integer, and that a table maps hash(key) % size to a bucket index. Here you will see why two different keys end up in the same bucket, how often that happens, and what it means for the design.
What a collision is
A collision happens when two different keys map to the same bucket index. Take the index formula:
index = hash(key) % sizeIf key_a != key_b but hash(key_a) % size == hash(key_b) % size, the two keys compete for one bucket. The table cannot drop either entry, so it needs a rule for storing both and finding each one later. Chaining and linear probing, covered in the next chapters, are two such rules.
There are two places a collision can occur. The table treats them the same way, but they have different causes.
| Kind | Condition | Cause |
|---|---|---|
| Hash collision | `hash(a) == hash(b)` for `a != b` | The hash function maps many keys to few integers |
| Index collision | `hash(a) % size == hash(b) % size` | Reducing a large range of integers to a small number of buckets |
Every hash collision is also an index collision. The reverse is not true. Two keys with different hash values can still share an index, and that is by far the more common case.
The pigeonhole argument
The pigeonhole principle says that if you place more than m items into m boxes, at least one box holds two or more items.
Apply it twice.
- Buckets. A table with 8 buckets that holds 9 keys must have a bucket with at least 2 keys. This is true for any hash function, however good.
- Hash values. A hash function returns a fixed-size integer, such as 32 or 64 bits. The set of possible keys is usually unbounded: strings of any length, tuples of any size. There are more possible keys than possible hash values, so some distinct keys must share a hash value.
The second point means you cannot fix collisions by choosing a better hash function. A better function spreads keys more evenly, but it cannot remove collisions. The only exception is perfect hashing, where the full set of keys is known in advance and a function is built to avoid collisions for that set. A general-purpose table accepts arbitrary keys later, so it cannot use that approach.
You can see the first case directly. This script puts nine words into eight buckets.
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
size = 8
words = ["apple", "banana", "cherry", "date", "elder",
"fig", "grape", "honey", "iris"]
buckets = {}
for w in words:
buckets.setdefault(string_hash(w, size), []).append(w)
for index in sorted(buckets):
print(index, buckets[index])
print("most keys in one bucket:", max(len(b) for b in buckets.values()))Whatever the individual hash values are, the last line prints a number of at least 2, because nine keys cannot fit into eight buckets one per bucket.
Collisions happen sooner than you expect
You might think collisions only matter once the table is nearly full. They do not. They appear well before that, for the same reason that in a room of 23 people there is about a 50% chance two share a birthday. This is the birthday problem.
Suppose a hash function spreads keys uniformly over m buckets. After inserting n keys, the probability that no two share a bucket is:
P(no collision) = (m / m) * ((m - 1) / m) * ((m - 2) / m) * ... * ((m - n + 1) / m)Each new key must avoid every bucket already taken, so each factor is a little smaller than the last. The product drops quickly.
def p_collision(n, m):
p_none = 1.0
for i in range(n):
p_none *= (m - i) / m
return 1 - p_none
m = 1000
for n in (10, 38, 100):
print(f"{n:>3} keys in {m} buckets: {p_collision(n, m):.1%} chance of a collision")The output is about 4% for 10 keys, about 51% for 38 keys, and about 99% for 100 keys. With 1000 buckets and only 100 keys, the table is 10% full, and a collision is still almost certain.
A useful estimate for the expected number of colliding pairs, assuming uniform hashing, is:
expected colliding pairs ≈ n * (n - 1) / (2 * m)For n = 100 and m = 1000 this is about 5 pairs. The number of pairs grows with the square of n, so doubling the number of keys roughly quadruples the pairs unless you also add buckets. This is one reason tables grow as they fill, which a later chapter covers under load factor and resizing.
Collisions in real hash functions
Equal hash values for different keys are not a theoretical curiosity. They occur in the hash functions you use every day.
CPython reserves -1 as an error code in its C-level hash interface, so the hash of the integer -1 is -2. That makes hash(-1) equal to hash(-2):
print(hash(-1), hash(-2), hash(-1) == hash(-2))
print({-1: "a", -2: "b"})Both entries are stored and retrieved correctly, because the dictionary compares keys with == after the hashes match. The collision costs a little time but does not change the result.
The polynomial hash from the earlier chapter has structured collisions too. The two-character strings "Aa" and "BB" give the same value, since 65 * 31 + 97 == 66 * 31 + 66 == 2112:
BIG = 1 << 30
print(string_hash("Aa", BIG) == string_hash("BB", BIG))
print(string_hash("AaAa", BIG) == string_hash("BBBB", BIG))
print(string_hash("AaBB", BIG) == string_hash("BBAa", BIG))Run this after the earlier definition of string_hash, or paste both snippets in one file. All three lines print True. Each block of "Aa" or "BB" can be swapped for the other without changing the hash. A string made of k such blocks therefore has 2^k variants that all share one hash value. An attacker who knows the hash function can use this to build many keys that all land in one bucket, which is the subject of the hash flooding chapter.
What collisions force on the design
Because collisions cannot be avoided, every hash table design must answer the same three questions.
- Where does the second key go? Chaining keeps a list per bucket. Open addressing looks for another free slot in the same array.
- How does lookup tell the keys apart? Matching the index is not enough. The table must store the full key next to each value and compare keys with
==after finding a candidate bucket. This is why a stored entry is a(key, value)pair and not just a value. - How is the number of collisions kept low? The table keeps the ratio of keys to buckets bounded by resizing, and relies on a hash function that spreads keys evenly.
Question 2 deserves emphasis. If a table compared only hash values, two different keys with the same hash would be mistaken for one key, and one would silently overwrite or return the other's value. Comparing the actual keys is what makes a collision a performance issue and not a correctness bug.
Common mistakes
- Treating the hash as unique. Code such as
if hash(a) == hash(b): same_item()is wrong. Equal hashes mean "possibly equal". Always confirm with==. - Expecting a collision-free table at low load. The birthday calculation shows that a sparsely filled table still has collisions. Design for them from the start.
- Blaming the hash function for every collision. Even a perfectly uniform function produces collisions when keys outnumber buckets, as the pigeonhole argument shows. A poor function makes the situation worse, but a good one cannot remove it.
- Forgetting that the modulo adds collisions. Two keys with different 64-bit hash values collide in the table whenever those values agree after
% size.
Exercises
Exercise
A table has 16 buckets and you insert 17 distinct keys with a hash function you have never seen. Can you say for certain that at least one bucket holds two or more keys? Explain why or why not.
Show answer
Yes. 17 keys into 16 buckets means the pigeonhole principle forces at least one bucket to contain two or more keys. This holds regardless of how good the hash function is, because it depends only on the counts of keys and buckets.
Exercise
Using the approximation n (n - 1) / (2 m), estimate the expected number of colliding pairs when 200 keys are hashed uniformly into 5000 buckets. Is the table more than a few percent full?
Show answer
200 199 / (2 5000) = 39800 / 10000 = 3.98, so about 4 colliding pairs are expected. The table is 200 / 5000 = 4% full, which is not many keys, yet several collisions are still expected.
Exercise
Why must a table store the full key alongside each value instead of storing only the value in the bucket?
Show answer
Different keys can map to the same bucket, so the bucket position alone cannot identify which key a value belongs to. On lookup the table compares the stored key with the requested key using ==, and only returns the value when they are equal. Without the stored key, a lookup for one key could return the value of a different key that collided with it.