edubun
English
1 / 18

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 questions

You will learn

  • Handle collisions with chains

Before this: Linked lists

1Explain

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));        // true
Output
2.5
false
true

14Problem

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.

Expected output
1 0 0 0 1 3 0
12 33 47
Your code
const 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).

Expected output
3
2
5
Your code
const 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

Mistake
const count = new Map();
for (const w of ["a", "b", "a"]) count.set(w, count.get(w) + 1);
console.log(count.get("a"));
Output
NaN
Fixed
const count = new Map();
for (const w of ["a", "b", "a"]) count.set(w, (count.get(w) || 0) + 1);
console.log(count.get("a"));
Output
2

get 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.

Next unitBinary search trees
Full text · The whole lesson as one text

Turning a key into a position

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.

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.

Collisions and chaining

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.

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 hash table of 7 buckets holding 12, 25, 33, 47 and 70, with h(k) = k mod 7. Choose a key and insert, find or delete. The step counter is 1 for the hash plus 1 for every key compared in the chain.
Real hash functions mix all the bits of a key, and well-designed libraries choose them so that ordinary data spreads evenly. MIT's 6.006 goes further and picks a hash function at random from a family, so that no fixed set of keys is bad every time. The plain k mod m in the lab is chosen because you can check it by hand.

Hash tables in JavaScript

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));        // true
BackgroundThe idea of hashing is credited to Hans Peter Luhn of IBM. Donald Knuth's history of searching records that in January 1953 Luhn wrote an internal IBM memorandum suggesting that records be put into numbered buckets, with chaining for the ones that collide. His hash functions worked on digits: add neighbouring pairs of digits and keep the last digit of each sum, so 31415926 becomes 4548. Other IBM engineers working on the IBM 701 had the same idea at about the same time, and the first published description came from Arnold Dumey in 1956.
Key points
  • 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.

Practice questions from Hash tables on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18