Hash functions
A hash function turns a key into an array index, as in the division method h(k) = k % m with m a prime, so a hash table can find, insert and delete in O(1) on average; strings use h = h * 31 + c.
A class has 50 students and you look one up by student number. Kept in an array, a linear search takes 25 comparisons on average; sorted, binary search still takes about 6. But if the numbers were exactly 0 to 49, a[number] would take one step. A hash table stretches that "just use the index" trick to any key: a function computes an index from the key, so finding, inserting and deleting are all O(1) on average. Python's dict, Java's HashMap, hash indexes in databases and a compiler's symbol table are all hash tables underneath. This lesson is about choosing that function.
From a key to an index
An array is fast because the address of a[i] is computed: the start address + i × the element size, with no comparisons. A hash table borrows this: allocate an array of m cells (each one a slot or bucket) and put key k in slot h(k). h is the hash function. To find k, compute h(k) again and look in that one slot.
The catch: there are far more possible keys than slots (billions of student numbers, a few dozen slots), so sooner or later two different keys compute the same index. That's a collision. You can't avoid collisions; you can only do two things: pick a hash function that keeps them rare (this lesson), and decide what to do when one happens (the next two lessons: open addressing and separate chaining).
A good hash function:
- is fast to compute: every lookup computes it once;
- gives equal keys the same index: otherwise what goes in can't be found again;
- spreads the keys evenly: it doesn't pile many keys into a few slots.
The table has 10 slots, h(k) = k % 10, and 23 is already in slot 3. Which key would collide with 23?
Which of these is not something a good hash function needs?
The division method: h(k) = k % m
For integer keys the usual choice is h(k) = k % m, which lands exactly in 0 to m − 1. Everything hinges on m. Real keys often follow a pattern: prices are multiples of 10, addresses are multiples of 8, IDs are all even. Take the 20 keys 10, 20, …, 200:
When the keys are multiples of d, k % m can only land on multiples of gcd(d, m), so only m / gcd(d, m) slots are usable. With m = 10 and keys that are multiples of 10, that's 1 slot; make m a prime and it shares no factor with almost any d, so every slot gets used. Running all 20 keys for real:
1#include <stdio.h>2 3void try_m(int m) {4 int cnt[20] = {0}, collide = 0, most = 0;5 for (int k = 10; k <= 200; k += 10) {6 int h = k % m;7 if (cnt[h] > 0) collide++; // this slot already has a key: a collision8 cnt[h]++;9 if (cnt[h] > most) most = cnt[h];10 }11 printf("m = %2d: %2d collisions, fullest slot holds %2d; per slot: ", m, collide, most);12 for (int i = 0; i < m; i++)13 printf("%d ", cnt[i]);14 printf("\n");15}16 17int main(void) {18 try_m(10);19 try_m(11);20 try_m(16);21 try_m(17);22 return 0;23}
m = 10: 19 collisions, fullest slot holds 20; per slot: 20 0 0 0 0 0 0 0 0 0 m = 11: 9 collisions, fullest slot holds 2; per slot: 1 1 2 2 2 2 2 2 2 2 2 m = 16: 12 collisions, fullest slot holds 3; per slot: 2 0 2 0 3 0 2 0 3 0 3 0 2 0 3 0 m = 17: 3 collisions, fullest slot holds 2; per slot: 1 1 1 2 1 1 1 1 1 1 2 1 1 2 1 1 1
Putting 20 keys into 11 slots forces at least 9 collisions, and m = 11 hits that minimum. m = 16 is poor too: multiples of 10 are even, so every odd slot stays empty. Powers of 2 are worse still: k % 2ʳ only looks at the last r bits of k, so the high bits never affect the index, and addresses and aligned numbers often end in a row of zeros. Hence the textbook rule: make m a prime that isn't close to a power of 2.
The 12 keys 4, 8, …, 48 go into a table with m = 16. How many slots do they use?
1#include <stdio.h>2 3int main(void) {4 int used[16] = {0}, slots = 0;5 for (int k = 4; k <= 48; k += 4) { // 4 8 12 … 48, 12 keys6 if (!used[k % 16]) slots++;7 used[k % 16] = 1;8 }9 printf("%d\n", slots);10 return 0;11}
Why is a power of 2 (say m = 16) a poor choice for m?
Counting collisions
✓Fill in collisions: put n keys in by k % m; landing in a slot that already has a key counts as one collision. Return the count. The keys are multiples of 8; compare m = 16 with m = 13.
m = 16: 10 m = 13: 0
1#include <stdio.h>2 3int collisions(int keys[], int n, int m) {4 int cnt[32] = {0}, c = 0;5 // for each key: h = keys[i] % m; if cnt[h] is already above 0, c++; then cnt[h]++6 return c;7}8 9int main(void) {10 int keys[12];11 for (int i = 0; i < 12; i++)12 keys[i] = 8 * (i + 1); // 8 16 24 … 9613 printf("m = 16: %d\n", collisions(keys, 12, 16));14 printf("m = 13: %d\n", collisions(keys, 12, 13));15 return 0;16}
Hashing strings
A string has to become an integer first. The obvious idea is to add up the character codes, but then "abc" and "cba" are equal, and so are all six of "stop", "pots", "tops", "spot", "opts" and "post": addition ignores order.
To make order count, weight each character by its position, as if reading a number in base 31:
h = 0; for each character c: h = h × 31 + c
"abc" is 97 × 31² + 98 × 31 + 99 = 96354, "cba" is 99 × 31² + 98 × 31 + 97 = 98274. Java's String.hashCode computes exactly this. 31 is a prime, and multiplying by 31 can be written (h << 5) - h, which is fast.
h = 0h = 97h = 3105h = 963541#include <stdio.h>2 3unsigned sum_hash(const char *s) { // the wrong way: just add them up4 unsigned h = 0;5 for (; *s; s++)6 h += (unsigned char)*s;7 return h;8}9 10unsigned poly_hash(const char *s) { // h = h * 31 + c11 unsigned h = 0;12 for (; *s; s++)13 h = h * 31 + (unsigned char)*s;14 return h;15}16 17int main(void) {18 const char *w[] = {"stop", "pots", "tops", "spot", "opts", "post", "abc", "cba"};19 int m = 101;20 printf("word sum %% 101 times 31 %% 101\n");21 for (int i = 0; i < 8; i++)22 printf("%-5s %5u %5u %8u %5u\n", w[i], sum_hash(w[i]), sum_hash(w[i]) % m,23 poly_hash(w[i]), poly_hash(w[i]) % m);24 return 0;25}
word sum % 101 times 31 % 101 stop 454 50 3540994 35 pots 454 50 3446974 46 tops 454 50 3566014 7 spot 454 50 3537154 33 opts 454 50 3418144 1 post 454 50 3446944 16 abc 294 92 96354 0 cba 294 92 98274 1
In the sum column all 6 words go to slot 50; times 31, the 6 words go to 6 different slots. When an unsigned overflows, C defines the result as taken modulo 2³², so it's still deterministic and nothing breaks: keep multiplying and take % m at the end.
Using h = h × 31 + c on "ab" and "ba", what does it print?
1#include <stdio.h>2 3unsigned poly(const char *s) {4 unsigned h = 0;5 for (; *s; s++)6 h = h * 31 + (unsigned char)*s;7 return h;8}9 10int main(void) {11 printf("%u %u\n", poly("ab"), poly("ba"));12 return 0;13}
If the hash value is just the sum of the character codes, which pair is sure to collide?
listen and silent are the same 6 letters in a different order, so their sums are equal (655 each) and they land in the same slot whatever m is. cat and cap differ in one letter, and abc has one more letter than ab, so their sums differ.Hashing a string
✓Fill in hash: h starts at 0, and for each character h = (h * 31 + c) % m. Print the indexes of three words with m = 13.
11 7 10
1#include <stdio.h>2 3int hash(const char *s, int m) {4 int h = 0;5 // for each character c: h = (h * 31 + c) % m6 return h;7}8 9int main(void) {10 printf("%d %d %d\n", hash("abc", 13), hash("cba", 13), hash("hash", 13));11 return 0;12}
The load factor α = n / m
However good the function, a table that's too full collides. With n keys in m slots, the load factor α = n / m is the average number of keys per slot.
| α | Meaning | What happens |
|---|---|---|
| 0.25 | 1 key per 4 slots | Almost no collisions, but space is wasted |
| 0.5 to 0.75 | The usual range | Few collisions, not much wasted space |
| close to 1 | Nearly full | Open addressing slows down sharply (run for real next lesson) |
| over 1 | More keys than slots | Only chaining can hold them: α keys per chain on average |
So a hash table watches α: once it passes a threshold (Java's HashMap uses 0.75), it allocates a new table about twice the size and moves every key across, recomputing its index. The chaining lesson draws this.
In exams: "what does a hash table's search efficiency depend on": the hash function, the collision-resolution method and the load factor α, not directly on the number of keys n. For the division method, m is "the largest prime not greater than the table length", e.g. 13 for a table of length 16.
A table has m = 8 slots holding 6 keys. What is the load factor α?
Taking m as "the largest prime not greater than the table length", what is m for a table of length 20?
Summary
Hash functions: turning a key into an index
- A hash table = an array + a hash function: compute the index and look there, O(1) on average
- Division method h(k) = k % m, with m a prime not close to a power of 2
- Strings: h = h × 31 + c, so a different order gives a different result
- Load factor α = n / m: fuller means more collisions; past a threshold, grow the table
1unsigned h = 0;2for (; *s; s++)3 h = h * 31 + (unsigned char)*s;4int slot = h % m;