Hash functions: from key to bucket index
A hash function turns a key into a bucket index. See keys map to buckets and how a good function spreads them evenly.
The idea
A gym gives member 12 locker 12 mod 5 = 2. Staff find the locker from the number alone, with no search.
A hash table works the same way. A hash function turns any key into a number, and the number picks one bucket.
Intuition
With 5 buckets, bucket = key mod 5. Key 12 goes to bucket 2 and key 9 goes to bucket 4.
The remainder of a division by m is always between 0 and m − 1. So mod m turns any hash value into a valid bucket index.
A string key needs a number first. Each character already has one: 'c' is 99, 'a' is 97, 't' is 116.
A string hash mixes all character codes into one number. Then mod m picks the bucket, exactly as for integer keys.
Complexity
An integer key hashes in one mod: O(1). A string key of length L takes one step per character: O(L).
Table operations are called O(1) because L is usually small and fixed. For long keys the hash itself is the main cost, so some languages cache a string's hash.
Pitfalls
Adding character codes ignores order. "stop", "pots" and "tops" all sum to 454 and share bucket 6.
The polynomial hash multiplies by 31 before each new character. Each position gets a different weight, so reordered letters give different hash values.
Keys 10 to 60 and m = 10 share the factor 10. Every key lands in bucket 0 and nine buckets stay empty.
Real keys often have patterns, such as even ids or prices in steps of 5. A prime table size shares no factor with such steps, so the keys still spread out.
Variations
Two keys can share a bucket, however good the hash. Chaining and open addressing are two ways to store them both.
A rolling hash updates the hash of a sliding window in O(1). Rabin–Karp, Bloom filters and consistent hashing build on hash functions.
Code
Pseudocode
place(keys, m)
counts ← m zeros
for each key in keys
h ← hash(key)
i ← h mod m
counts[i] ← counts[i] + 1
return counts
Python
def place(keys, m):
counts = [0] * m
for key in keys:
h = hash(key)
i = h % m
counts[i] += 1
return counts
JavaScript
function place(keys, m) {
const counts = new Array(m).fill(0);
for (const key of keys) {
const h = hash(key);
const i = ((h % m) + m) % m;
counts[i]++;
}
return counts;
}
Java
int[] place(int[] keys, int m) {
int[] counts = new int[m];
for (int key : keys) {
int h = Integer.hashCode(key);
int i = Math.floorMod(h, m);
counts[i]++;
}
return counts;
}
Practice problems (7)
Bucket for keys Warm-up
A table has 7 buckets and uses key mod 7 as its bucket index. Hash the keys 15, 22, 40, 9, 29 in this order and answer each question before the step plays.
Why mod table size Warm-up
A hash function can return any whole number, such as 98262 for "cat". A table with m buckets then computes hash(key) mod m. Why mod m?
Pick the better hash Standard
A table stores 10,000 English words in 1,009 buckets. Which hash spreads the words most evenly over the buckets?
Predict an anagram's bucket Standard
This hash adds up the character codes of a string. The word "stop" lands in bucket 6 of a 7-bucket table. What does the code print for "pots"?
Bucket index of every key Standard
A table has m buckets and uses the key itself as its hash value. Return the bucket index of each key in keys, in order.
A bucket index must lie between 0 and m − 1, also for negative keys. For example, −3 goes to bucket 1 when m = 4, because −3 = −1 · 4 + 1.
Bucket histogram Standard
A table has m buckets and sends a key to bucket key mod m. Count how many keys from keys land in each bucket. Count a repeated key every time it appears.
Return an array of length m whose entry i is the number of keys in bucket i.
Implement a polynomial string hash Challenge
Compute the polynomial hash of text. Start with h = 0. For each character c, from left to right, set h = (h · 31 + code(c)) mod 1,000,000,007, where code(c) is the character code ('a' is 97).
Return the final h. Reduce h after every character, because the unreduced value overflows quickly.
Related topics
Next on the path: Hash tables with separate chaining