Handle Collisions in Hash Tables
Core idea
A hash table maps a key to a bucket index. Distinct keys can collide; equality, not the bucket index alone, identifies a key. This teaching table uses separate chains of integer-key pairs and key % capacity as its bucket function. With good distribution and bounded load factor n/capacity, expected lookup is constant; worst-case collisions can force a linear scan. Python dict is not this chained implementation.
buckets = [[] for _ in range(3)]for k,v in [(1,'A'),(4,'B')]: buckets[k%len(buckets)].append((k,v))def lookup(k): for key,value in buckets[k%len(buckets)]: if key == k: return value raise KeyError(k)print(buckets[1])print(lookup(4))Both keys occupy bucket 1, but equality distinguishes them. This fixture inserts unique keys only.
Rehash when capacity changes
items = [(1,'A'),(4,'B'),(7,'C')]new = [[] for _ in range(5)]for k,v in items: new[k%len(new)].append((k,v))print([len(bucket) for bucket in new])print(new[4])Recompute the index for every key; copying bucket positions would break lookup.
Common mistake
Equal hash values do not imply equal keys. A mapping must update an existing equal key instead of adding a second copy. Do not promise constant worst-case time.
Practice
Add put(k,v) that replaces a matching key in its bucket. Resize at a chosen load threshold, then test colliding keys and missing lookups.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Hash table
Check your understanding of hash table.
What is printed?
print(2%4,6%4)What is printed?
print(len({1:"A",4:"B"}))Why rehash on capacity change?
Worst case lookup with all keys in one chain?