Hash functions and hash tables
Map keys to buckets with a hash function and the remainder by the table size, predict collisions, and say what makes a hash function good.
It opens on
A table has 7 buckets, and a key goes to bucket key % 7. 12 is already in its bucket. Where does 40 go, and is that bucket free?
Why it matters
Hash tables give Python's dict and set, database indexes and caches their average constant-time lookups, and choosing a hash and a table size that spread keys evenly is what keeps them fast; computing bucket indexes by hand is a standard exam question.
Good to know first
- Big-O, Big-Omega and Big-Theta: O(1) against O(n) and O(log n)
- Lists: indexing and mutation: a list of m slots indexed 0 to m − 1
- Values, types and expressions: % gives the remainder
Step by step
Keys to buckets
Compute the bucket of each key with key % m, place keys in a table, and recognise a collision.
12 % 7 is 5, 25 % 7 is 4 and 31 % 7 is 3, so those keys go to buckets 5, 4 and 3.
A common mix-up
Collisions only happen when the table is full.
In fact: With 5 keys in 7 buckets, two already share a bucket; collisions are expected long before the table fills.
Spreading keys
Say what makes a hash function good, and show how a table size that shares a pattern with the keys piles them into one bucket.
So every key lands in bucket 0, and the table acts like one long list. A lookup then checks every key, O(n), and the hash table is no better than a list.
A common mix-up
Any hash function is fine because the table handles collisions.
In fact: a hash that piles keys into few buckets turns every O(1) lookup into an O(n) scan.
Hashing strings
Hash a string by summing character codes and by a polynomial, and explain why the polynomial spreads anagrams apart.
The same happens to every anagram. listen, silent and enlist all summed to 655 and landed in bucket 6 with m = 11.
three anagrams
A common mix-up
A hash that uses every character is automatically good.
In fact: sum_hash uses every character yet makes every anagram collide; the order must matter too.
Try it
With m = 7, place 14, 21 and 9. Which of them collide?Answer
14 % 7 = 0 and 21 % 7 = 0 collide in bucket 0; 9 goes to bucket 2
Hint: Multiples of 7 give 0
Keys 105, 215, 325 and 435 with m = 5. What buckets, and what would m = 7 give?Answer
All 0 with m = 5, since they end in 5; with m = 7, 0, 5, 3 and 1
Hint: 105 = 15 × 7
What is poly_hash("ba")?Answer
31 × 98 + 97 = 3135
Hint: Start from h = 0, then h = 98, then 31 × 98 + 97
Which buckets do 40 and 7 go to?Answer
40 % 7 = 5 and 7 % 7 = 0, so buckets 5 and 0.
What are the buckets with m = 7 instead?Answer
3, 5, 0, 2 and 5, so the keys spread over four buckets, with one collision.
