Sub topic 5
Collisions are unavoidable
This chapter assumes you know how a hash function turns a key into an integer and how hash(key) % size gives a bucket index. It also assumes basic Big-O and Python. Here you will see why two keys sometimes land in the same bucket, and why no clever design removes that possibility.
What a collision is
A collision happens when two different keys map to the same bucket index. With size = 8, the index of every key is a number from 0 to 7. If index("apple") and index("pear") are both 3, those keys collide.
A collision does not mean the hash function is broken. The two keys may even have different full hash values. Reducing a large integer modulo a small table size throws information away, and that is where most collisions come from.
The pigeonhole principle
If you put more than 8 items into 8 buckets, at least one bucket holds two items. This is the pigeonhole principle. A hash table faces a stronger version of it, because the set of possible keys is far larger than the set of buckets. There are infinitely many strings and only a few buckets. No function from keys to a smaller index range can give every key its own index.
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
keys = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
indexes = [string_hash(k, 8) for k in keys]
print(len(keys), "keys,", len(set(indexes)), "distinct indexes")
print(len(set(indexes)) < len(keys))Nine keys cannot fit into eight distinct indexes, so the last line always prints True. This holds for any hash function.
Collisions arrive earlier than you expect
You might think collisions only matter once the table is nearly full. They do not. This is the birthday problem. In a group of 23 people, the chance that two share a birthday is about 50%, even though there are 365 possible days.
The same math applies to buckets. If each key is equally likely to land in any bucket, the chance that no two of n keys collide is the product of (m - i) / m for i from 0 to n - 1, where m is the bucket count.
def collision_probability(n_keys, n_buckets):
p_no_collision = 1.0
for i in range(n_keys):
p_no_collision *= (n_buckets - i) / n_buckets
return 1 - p_no_collision
print(round(collision_probability(5, 8), 3))
print(round(collision_probability(23, 365), 3))This prints 0.795 and 0.507. Five keys in an eight-bucket table, which is only 62% full, already collide about 80% of the time.
Why a better hash function is not the answer
A good hash function spreads keys evenly, and that lowers the number of collisions. Even a perfectly uniform function cannot reduce it to zero, for the two reasons above: the pigeonhole principle and the birthday effect. There is one narrow exception. If you know the full key set in advance, you can build a perfect hash function with no collisions. General-purpose tables take arbitrary keys at run time, so they cannot rely on that.
So a hash table design has to include a plan for collisions. The plan must keep lookups correct, and it should keep them fast.
What the plan must guarantee
Any collision strategy must answer one question: when two keys share an index, how does get find the right one? That is why tables store the key together with the value and compare keys with == after hashing. The hash narrows the search to one bucket, and the equality check picks the right entry.
The next chapters cover the two main strategies:
| Strategy | Where colliding keys go |
|---|---|
| Separate chaining | Into a list kept inside the same bucket |
| Open addressing | Into another free slot in the array itself |
Exercise
A table has 100 buckets and holds 101 keys. Can you say for certain that a collision has occurred? Would your answer change if the table held only 10 keys?
Show answer
Yes, with 101 keys in 100 buckets, the pigeonhole principle guarantees at least one bucket holds two keys. With 10 keys you cannot be certain, because all 10 could land in different buckets. A collision is still fairly likely, though. The chance of at least one is about 1 - (100 × 99 × ... × 91) / 100^10, which is roughly 37%.