Sub topic 2
Collisions Are Unavoidable
Assume you know arrays, modulo, loops, and basic Big-O notation. This chapter focuses on how a hash table handles two different keys that map to the same position.
Why collisions happen
A hash table has a finite number of buckets, but it may accept many possible keys. A hash function converts a key into an integer, and modulo maps that integer to a bucket:
index = hash(key) modulo number of buckets
Different keys can produce the same index. This event is a collision. A collision does not mean the keys are equal. It means only that they need the same first storage position.
Resolving collisions with chaining
Separate chaining stores a collection of entries in each bucket. A lookup computes the bucket index, then compares the requested key with entries in that bucket.
def bucket(key, size):
return sum(ord(ch) for ch in key) % size
buckets = [[] for _ in range(5)]
for key, value in [("ab", 1), ("ba", 2)]:
buckets[bucket(key, len(buckets))].append((key, value))
print(buckets[0]) # Both keys collide and share this bucket.The average lookup remains constant when buckets stay short. In a bad case, one bucket can contain every entry, making lookup O(n).
Resolving collisions with linear probing
Open addressing stores entries directly in the array. With linear probing, a collision makes the table check the next slot, then the next, wrapping around when necessary.
slots = [None] * 5
for key in ["ab", "ba"]:
i = bucket(key, len(slots))
while slots[i] is not None:
i = (i + 1) % len(slots)
slots[i] = key
print(slots)Linear probing is cache-friendly, but clusters of occupied slots can make operations slower.
Deleting from an open-addressing table
Deletion needs care. Replacing an entry with an empty slot can make a later lookup stop too soon. Instead, implementations use a tombstone: a marker meaning “an entry was here.” Lookups continue past tombstones, while new entries may reuse them.
Load factor and resizing
The load factor is the number of stored entries divided by the number of slots. As it rises, collisions become more likely.
| Strategy | Typical resize threshold | Collision storage |
|---|---|---|
| Chaining | About 0.75 | Per-bucket lists |
| Linear probing | Often 0.5 or lower | Array slots |
When the threshold is exceeded, the table allocates a larger array and rehashes every live entry. The index can change because the array size changed.
Exercise
Why can a linear-probing table not treat a deleted slot as empty?
Show answer
An empty slot can make a lookup stop before it reaches a key stored farther along the probe sequence.