Hash functions
A hash function turns a key into an array index, giving O(1) lookups on average: integers use h(k) = k % m with a prime m, strings use h = h * 31 + c, and the load factor α = n / m sets how many collisions occur.
A class has 50 students and you look one up by student number. With the numbers in a vector, a sequential 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 "use the index directly" idea to any key: a function computes an index from the key, and lookup, insertion and deletion all take O(1) on average. C++'s unordered_map, Java's HashMap, database hash indexes and compiler symbol tables all sit on it. This lesson is about choosing that function.
From key to index
An array is fast because the address of a[i] is computed: base address + i × element size, with no comparisons. A hash table borrows that: allocate an array of length m (each cell is a slot or bucket) and put key k in the cell at index h(k). h is the hash function. To find k, compute h(k) again and look in that one cell.
The catch: there are far more possible keys than cells (an int has over 4 billion values, the table has a few dozen cells), so two different keys will sooner or later compute the same index. That is a collision. Collisions can't be avoided, so you 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 equal indexes: otherwise what you store can't be found again;
- spreads keys evenly: it doesn't crowd many keys into a few cells.
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
The usual choice for integer keys is h(k) = k % m, which lands exactly in 0 to m − 1. Everything depends on m. Real keys often follow a pattern: prices are multiples of 10, addresses multiples of 8, IDs 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) cells get used. With m = 10 and multiples of 10, that's 1 cell; make m a prime and it is coprime to almost every d, so every cell gets used. Run the 20 keys:
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6void try_m(int m) {7 vector<int> cnt(m, 0); // cnt[h]: how many keys are in cell h8 int collide = 0, most = 0;9 for (int k = 10; k <= 200; k += 10) {10 int h = k % m;11 if (cnt[h] > 0) collide++; // this cell already holds a key: a collision12 cnt[h]++;13 most = max(most, cnt[h]);14 }15 cout << "m = " << m << ": " << collide << " collisions, fullest cell holds " << most << "; per cell: ";16 for (int c : cnt)17 cout << c << " ";18 cout << "\n";19}20 21int main() {22 try_m(10);23 try_m(11);24 try_m(16);25 try_m(17);26 return 0;27}
m = 10: 19 collisions, fullest cell holds 20; per cell: 20 0 0 0 0 0 0 0 0 0 m = 11: 9 collisions, fullest cell holds 2; per cell: 1 1 2 2 2 2 2 2 2 2 2 m = 16: 12 collisions, fullest cell holds 3; per cell: 2 0 2 0 3 0 2 0 3 0 3 0 2 0 3 0 m = 17: 3 collisions, fullest cell holds 2; per cell: 1 1 1 2 1 1 1 1 1 1 2 1 1 2 1 1 1
20 keys in 11 cells need at least 9 collisions, and m = 11 hits exactly that minimum. m = 16 is poor too: multiples of 10 are all even, so every odd cell stays empty. Powers of 2 have a worse problem: k % 2ʳ looks only at the last r bits of k, so the high bits never change the index, and addresses or aligned numbers often end in a run of zero bits. Hence the textbook rule: make m a prime not too close to a power of 2.
The 12 keys 4, 8, …, 48 go into a table with m = 16. How many cells get used?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<bool> used(16, false);7 int slots = 0;8 for (int k = 4; k <= 48; k += 4) { // 4 8 12 … 48, 12 keys9 if (!used[k % 16]) slots++;10 used[k % 16] = true;11 }12 cout << slots << "\n";13 return 0;14}
Why is a power of 2 (say m = 16) a poor choice for m?
Counting collisions
✓Fill in collisions - put each key in by k % m, count one collision whenever it lands in a cell that already holds a key, and return the count. The keys are multiples of 8; compare m = 16 with m = 13.
m = 16: 10 m = 13: 0
1#include <iostream>2#include <vector>3using namespace std;4 5int collisions(const vector<int>& keys, int m) {6 vector<int> cnt(m, 0);7 int c = 0;8 // for each key k: h = k % m; if cnt[h] is already above 0, c++; then cnt[h]++9 return c;10}11 12int main() {13 vector<int> keys;14 for (int i = 1; i <= 12; i++)15 keys.push_back(8 * i); // 8 16 24 … 9616 cout << "m = 16: " << collisions(keys, 16) << "\n";17 cout << "m = 13: " << collisions(keys, 13) << "\n";18 return 0;19}
Hashing strings
A string has to become an integer first. The obvious idea is to add up the character codes, but then "abc" equals "cba", and the six words "stop" "pots" "tops" "spot" "opts" "post" all come out the same: addition ignores order.
To make order count, multiply each character by a weight for its position, as if reading a base-31 number:
h = 0; for each character c: h = h × 31 + c
"abc" is 97 × 31² + 98 × 31 + 99 = 96354 and "cba" is 99 × 31² + 98 × 31 + 97 = 98274. Java's String.hashCode works this way. 31 is a prime, and multiplying by 31 can be written (h << 5) - h, which is fast.
h = 0h = 97h = 3105h = 963541#include <cstdio>2#include <string>3#include <vector>4using namespace std;5 6unsigned sum_hash(const string& s) { // the wrong way: just add them up7 unsigned h = 0;8 for (char c : s)9 h += (unsigned char)c;10 return h;11}12 13unsigned poly_hash(const string& s) { // h = h * 31 + c14 unsigned h = 0;15 for (char c : s)16 h = h * 31 + (unsigned char)c;17 return h;18}19 20int main() {21 vector<string> w = {"stop", "pots", "tops", "spot", "opts", "post", "abc", "cba"};22 unsigned m = 101;23 printf("word sum %% 101 × 31 %% 101\n");24 for (const string& s : w)25 printf("%-5s %5u %5u %8u %5u\n", s.c_str(), sum_hash(s), sum_hash(s) % m,26 poly_hash(s), poly_hash(s) % m);27 return 0;28}
word sum % 101 × 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 cell 50; with × 31 they go to 6 different cells. C++ defines unsigned overflow as wrapping modulo 2³², so the result is still deterministic and nothing breaks: you can keep multiplying and take % m at the end. Not so with int: signed overflow is undefined behaviour. The table uses printf because lining up columns is easier than with cout; the two can be mixed.
Using h = h × 31 + c on "ab" and "ba", what does it print?
1#include <iostream>2#include <string>3using namespace std;4 5unsigned poly(const string& s) {6 unsigned h = 0;7 for (char c : s)8 h = h * 31 + (unsigned char)c;9 return h;10}11 12int main() {13 cout << poly("ab") << " " << poly("ba") << "\n";14 return 0;15}
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.String hash
✓Fill in hash_str - h starts at 0, and for each character h = (h * 31 + c) % m. Print the index of three words for m = 13.
11 7 10
1#include <iostream>2#include <string>3using namespace std;4 5int hash_str(const string& s, int m) {6 int h = 0;7 // for each character c: h = (h * 31 + c) % m8 return h;9}10 11int main() {12 cout << hash_str("abc", 13) << " " << hash_str("cba", 13) << " " << hash_str("hash", 13) << "\n";13 return 0;14}
The load factor α = n / m
However good the function, a table that is too full will collide. With n keys and m cells, the load factor α = n / m is the average number of keys per cell.
| α | Meaning | What happens |
|---|---|---|
| 0.25 | 1 key per 4 cells | hardly any collisions, but wasted space |
| 0.5-0.75 | the usual range | few collisions, not much wasted space |
| close to 1 | nearly full | open addressing slows down sharply (run in the next lesson) |
| above 1 | more keys than cells | only chaining can hold them: α keys per chain on average |
So a hash table watches α: past a threshold (0.75 for Java's HashMap, 1 by default for C++'s unordered_map) it allocates a new table about twice as big and moves every key across, computing its index again. The chaining lesson draws this.
In exams: "What does a hash table's search efficiency depend on?" The hash function, the collision method and the load factor α, not directly on the number of keys n. For the division method, m is "the largest prime not above the table size", so a table of 16 uses 13.
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?
With the STL
unordered_set<K> and unordered_map<K, V> do everything in this lesson for you: std::hash<K> turns the key into a size_t, then % the bucket count gives the bucket. In g++'s standard library hash<int> is the number itself, so an integer key's bucket is k % bucket count; hash<string> stirs in every byte, the same idea as h × 31 + c, only mixed harder. The bucket counts follow this lesson's reasoning too: they are all primes.
1#include <iostream>2#include <unordered_set>3using namespace std;4 5int main() {6 for (int n : {10, 100, 1000}) {7 unordered_set<int> s;8 s.reserve(n); // about to hold n keys: open enough buckets first9 cout << "reserve(" << n << "): " << s.bucket_count() << " buckets\n";10 }11 12 unordered_set<int> s;13 for (int k = 10; k <= 200; k += 10) // the same 20 multiples of 1014 s.insert(k);15 cout << s.size() << " keys, " << s.bucket_count() << " buckets, α = " << s.load_factor() << "\n";16 17 // a point (x, y) as the key: there is no hash<pair<int, int>>, so build one integer18 unordered_set<long long> seen;19 int xs[] = {1, 2, 1, 3}, ys[] = {2, 1, 2, 3};20 for (int i = 0; i < 4; i++) {21 long long key = (long long)xs[i] * 1000000 + ys[i]; // no clashes while y < 100000022 cout << "(" << xs[i] << ", " << ys[i] << "): " << (seen.count(key) ? "seen" : "new") << "\n";23 seen.insert(key);24 }25 return 0;26}
reserve(10): 11 buckets reserve(100): 103 buckets reserve(1000): 1031 buckets 20 keys, 29 buckets, α = 0.689655 (1, 2): new (2, 1): new (1, 2): seen (3, 3): new
reserve(100) gives 103 buckets and reserve(1000) gives 1031: primes a little above what was asked for. The 20 multiples of 10 go into 29 buckets, α is under 0.7, and since 29 and 10 are coprime they don't crowd into one cell the way they did with m = 10.
| Key type | Hash used | Watch out |
|---|---|---|
int, long long, char | hash is the value itself, then % bucket count | prime bucket counts spread patterned keys |
string | hash<string> stirs every byte | O(length) per hash: long strings are not cheap keys |
pair, your own struct | the standard library has none | build one integer or string; or write a hash function object and pass it in |
In interviews: unordered_map<pair<int, int>, int> doesn't compile as written, because there is no hash<pair<int, int>>. The usual fixes are to pack the two numbers into one long long (x × a big enough number + y), or to use map<pair<int, int>, int> instead (a red-black tree, needs only <, O(log n)).
The line unordered_map<pair<int, int>, int> m; doesn't compile. Why?
unordered_map first turns the key into a number with hash<Key>, then takes it % the bucket count. int and string come with a hash; pair doesn't. A pair can be compared with == and with <, so map<pair<int, int>, int> works fine.Pack the point (x, y) into one integer key: key = x * 1000000 + y (y is less than 1000000). What is the key of the point (3, 7)?
Summary
Hash functions: turning keys into indexes
- hash table = array + hash function: compute the index and look, 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
- unordered_set's bucket counts are primes; a pair key you pack yourself
1unsigned h = 0;2for (char c : s)3 h = h * 31 + (unsigned char)c;4size_t slot = h % m;