Sub topic 4
Collisions are unavoidable
This chapter assumes you can read basic Python, know what a hash function is (a deterministic map from arbitrary input to a fixed-size value), and are comfortable with powers of two and the modulo operator. It covers why two different inputs must sometimes share a hash value, and why you should design for that fact instead of hoping to avoid it.
The pigeonhole principle
A collision happens when two different inputs produce the same hash value. The pigeonhole principle explains why this cannot be avoided. If you place more than n items into n boxes, at least one box holds two or more items.
A hash function with a 32-bit output has 2^32 possible values, which is 4,294,967,296 boxes. The set of possible inputs is far larger. There are more than 2^32 strings of just six bytes (2^48 of them), and the input length is unlimited. So many inputs must map to each output value. No choice of function, however clever, can change this.
Seeing a collision
You can find collisions in a small hash quickly. The code below keeps only the first byte of a SHA-256 digest, which leaves 256 possible values. By the pigeonhole principle, hashing 257 distinct inputs must produce at least one collision.
import hashlib
def tiny_hash(s: str) -> int:
return hashlib.sha256(s.encode()).digest()[0] # 8-bit hash
seen = {}
for i in range(257):
word = f"item-{i}"
h = tiny_hash(word)
if h in seen:
print(f"collision: {seen[h]!r} and {word!r} -> {h}")
break
seen[h] = wordThe loop usually stops well before 257 items. By the time you have hashed around 20 items, a collision is already likely. Chapter 9 explains why with the birthday bound. The pigeonhole principle only guarantees the worst case.
Collisions in hash tables
A hash table stores each key in a bucket chosen from its hash value. Two keys that collide land in the same bucket, and the table must still tell them apart. Two common strategies handle this:
- Chaining: each bucket holds a list of entries. Lookup hashes the key, then compares keys inside the list.
- Open addressing: if the bucket is taken, the table probes other buckets in a fixed sequence until it finds a free one or the right key.
In both cases the table compares the actual keys after the hash. The hash narrows the search, but equality of hash values never proves equality of keys.
class ChainedTable:
def __init__(self, buckets=8):
self.buckets = [[] for _ in range(buckets)]
def _index(self, key):
return hash(key) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
def get(self, key):
for k, v in self.buckets[self._index(key)]:
if k == key:
return v
raise KeyError(key)
t = ChainedTable(buckets=2)
for name in ["ann", "bob", "cy", "di"]:
t.put(name, len(name))
print(t.get("cy"))
print([len(b) for b in t.buckets])With only two buckets and four keys, at least one bucket must hold two or more keys. The table still works, because get compares keys inside the bucket.
Common errors
- Treating equal hashes as equal inputs. Always compare the originals when correctness matters.
- Assuming a large output removes collisions. A larger output makes them rarer, not impossible.
- Using a hash value as a unique ID. A truncated or short hash can collide with other items.
Exercise
A hash function outputs 10 bits. What is the smallest number of distinct inputs that guarantees at least one collision, and why?
Show answer
1,025 inputs. A 10-bit output has 2^10 = 1,024 possible values. By the pigeonhole principle, 1,025 distinct inputs must put at least two into the same value. A collision can occur earlier, but only at 1,025 inputs is it guaranteed.
Exercise
A teammate says, "Our hash table never loses data, so our hash function must have no collisions." What is wrong with this reasoning?
Show answer
Hash tables handle collisions by storing keys alongside values and comparing keys after hashing, using chaining or probing. The table keeps working even when many keys collide. Collisions only affect speed, because crowded buckets take longer to search.