5 / 7 · Intermediate
Hash tables
With 47 stored in a table of 7 buckets, the computer goes straight to bucket 47 mod 7 = 5 instead of searching the whole table.
Jump to the 10 practice questions1Explain
Let the key say where it goes
So far, finding a value meant searching: up to n steps in an unsorted array or a linked list. Arrays, though, can reach any position in one step. What if the key itself told you the position? If your keys were small whole numbers, say student numbers from 0 to 99, you could keep an array of 100 cells and store student k in cell k. MIT's notes call this a direct access array. It fails when the possible keys are huge, like phone numbers or words, because you cannot afford a cell for every possible key.
2Explore
A hash function
A hash function solves that by squeezing any key into a small range of positions, 0 to m − 1. A simple one for whole numbers is h(k) = k mod m, the remainder after dividing by m. The array of m cells is the hash table, and its cells are often called buckets. To store 47 with m = 7, compute 47 mod 7 = 5 and put it in bucket 5. To find 47 later, compute the same thing and look only in bucket 5.
Insert the keys one by one. Each goes into bucket k mod 7: 1 step for the hash, 1 for the write.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
3Problem
Where 47 goes
With h(k) = k mod 7, which bucket does 47 go into?
Hint
47 = 6 × 7 + 5.
Solution
Answer: 5
47 = 6 × 7 + 5, so the remainder is 5.
4Explore
Collisions and chains
There is a problem. With 7 buckets and more than 7 possible keys, some keys must share a bucket: 12, 33 and 47 all give remainder 5. This is called a collision, and MIT's notes point out that it cannot be avoided, by the pigeonhole principle. The usual remedy is chaining: each bucket holds a small list, a chain, of every key that hashed there. Finding 47 then costs 1 step for the hash plus one comparison for each key checked in chain 5. If 12 and 33 are ahead of it, that is 1 + 3 = 4 steps.
12, 33 and 47 share bucket 5. Finding a key costs 1 for the hash plus one comparison per key checked in its chain.
Press a button: each one runs one operation and shows what it cost.
[12,25,33,47,70]Total steps 0
5Problem
Finding 47
The table holds 12, 25, 33, 47, 70 (inserted in that order) with m = 7. How many steps does finding 47 take (1 for the hash plus keys compared)?
Hint
Hash, then compare 12, 33, 47.
Solution
Answer: 4
Bucket 5 holds 12, 33, 47. Hash 1, then compare 12, 33, 47: 1 + 3 = 4.
6Problem
Finding 12
Same table: how many steps for finding 12?
Hint
12 is first in its chain.
Solution
Answer: 2
12 is first in chain 5: 1 for the hash + 1 comparison = 2.
7Problem
A missing key
Same table: 19 is not stored. How many steps does a search for 19 take?
Hint
19 mod 7 = 5.
Solution
Answer: 4
19 mod 7 = 5. Compare with all three keys in chain 5, then stop: 1 + 3 = 4.
8Problem
A collision
What is a collision?
Hint
12 and 33 both give 5.
Solution
Answer: Two different keys hashing to the same bucket
12 and 33 are different keys that both give 5 with m = 7.
9Problem
Why collisions are certain
Why can no hash function avoid collisions when there are more possible keys than buckets?
Hint
More pigeons than holes.
Solution
Answer: The pigeonhole principle
More keys than buckets means at least two keys share a bucket (MIT lecture 4).
10Explore
How long are the chains?
How long are the chains? If the keys spread evenly, each chain holds about n/m keys, a number called the load factor. Keep m about as large as n and the chains stay short, so finding, inserting and deleting take a constant number of steps on average. The danger is a bad spread. If every key hashes to the same bucket, one chain holds all n keys and the table is no better than a linked list. In the lab, set 7 buckets and insert 14, 21 and 28: they all land in bucket 0.
A bad spread: every key here is a multiple of 7, so all of them land in bucket 0 and the table searches like a list.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
11Problem
The load factor
Same table: what is the load factor n/m? (two decimal places)
Hint
5 keys over 7 buckets.
Solution
Answer: 0.71
5 keys / 7 buckets = 0.714..., about 0.71.
12Problem
Every key in one bucket
If every key lands in the same bucket, how does finding a key behave?
Hint
One long chain.
Solution
Answer: Like searching a linked list of n keys
One chain holds all n keys, so a search may compare with all of them: Θ(n).
13Explain
Map and Set
You seldom write a hash table yourself, because JavaScript has Map and Set. The ECMAScript specification says they "must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements". In other words, map.get(key) and set.has(x) must be faster than searching the whole collection. MDN adds that a Map keeps keys in insertion order and, unlike a plain object, contains no default keys that could collide with yours.
const price = new Map();
price.set("apple", 1.2);
price.set("bread", 2.5);
console.log(price.get("bread")); // 2.5, no search through the list
console.log(price.has("milk")); // false
const seen = new Set([4, 8, 15]);
console.log(seen.has(8)); // true2.5
false
true14Problem
What the specification asks of Map
What does the ECMAScript specification require of Map access times?
Hint
Faster than a search through every key, on average.
Solution
Answer: Sublinear in the number of elements, on average
Maps "must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear".
15Practice
Write the hash function
Write the hash function. It should print the chain lengths 1 0 0 0 1 3 0 and then the keys in bucket 5, 12 33 47.
1 0 0 0 1 3 0
12 33 47const m = 7;
const buckets = Array.from({ length: m }, () => []);
function h(k) {
// Return the remainder of k divided by m.
return 0;
}
for (const k of [12, 25, 33, 47, 70]) buckets[h(k)].push(k);
console.log(buckets.map((b) => b.length).join(" "));
console.log(buckets[5].join(" "));
Hint
The remainder is k % m; Math.floor(k / m) is the quotient.
A solution
const m = 7;
const buckets = Array.from({ length: m }, () => []);
function h(k) {
return k % m;
}
for (const k of [12, 25, 33, 47, 70]) buckets[h(k)].push(k);
console.log(buckets.map((b) => b.length).join(" "));
console.log(buckets[5].join(" "));16Practice
Count words with a Map
Count the words with a Map. It should print 3, 2 and 5 (five different words).
3
2
5const words = "the cat and the dog and the bird".split(" ");
const count = new Map();
for (const w of words) {
// Set count for w to (its current count, or 0) + 1.
}
console.log(count.get("the"));
console.log(count.get("and"));
console.log(count.size);
Hint
Read the current count (or 0) and add 1.
A solution
const words = "the cat and the dog and the bird".split(" ");
const count = new Map();
for (const w of words) {
count.set(w, (count.get(w) || 0) + 1);
}
console.log(count.get("the"));
console.log(count.get("and"));
console.log(count.size);17Explain
Common mistakes
const count = new Map();
for (const w of ["a", "b", "a"]) count.set(w, count.get(w) + 1);
console.log(count.get("a"));NaNconst count = new Map();
for (const w of ["a", "b", "a"]) count.set(w, (count.get(w) || 0) + 1);
console.log(count.get("a"));2get returns undefined for a key that is not there yet, and undefined + 1 is NaN. Start from 0.
18
Summary
- A hash function turns a key into a bucket number; k mod m is a simple one.
- Collisions are unavoidable; chaining keeps a list in each bucket.
- With load factor n/m kept small, find, insert and delete take constant steps on average.
- JavaScript Map and Set must be faster than linear on average.