Lesson 2: Finding Needles Without Scanning the Haystack — Hash Tables and Collisions
Learning objective
Students will compute array bucket indices using a deterministic hash function (h(k) mod M), build a 7-bucket hash table with separate chaining to resolve collisions, and compare the number of comparisons needed for an unsorted list scan vs. a hash table lookup.
Materials
- Printed or whiteboard 7-bucket hash table grid (
Buckets 0 through 6)
- Alphabet position strip (
A=1, B=2, C=3, ..., Z=26) for quick arithmetic hashing by hand
Vocabulary
- Key–Value Pair: A unique identifier (key, such as a student ID or word) stored alongside its associated data (value, such as a grade or definition).
- Hash Function (
h(k)): A deterministic math rule that converts any key k into an integer bucket index 0, 1, ..., M - 1.
- Collision: When two different keys (
k1 != k2) produce the exact same bucket index (h(k1) == h(k2)).
- Separate Chaining: Storing a short linked list (chain) of key–value pairs inside each bucket so colliding keys can share a bucket without overwriting each other.
- Load Factor (
α = n / M): The ratio of stored items (n) to total buckets (M), connecting directly to Grade 6 Mathematics: Ratios.
Lesson flow
1. Opening: Why Not Just Scan a List? (8 min)
- Suppose a school library database stores
n = 70,000 book barcodes in an unsorted list.
- To check if barcode
B-94821 is checked out, a linear scan checks item 1, item 2, item 3... taking 35,000 comparisons on average and 70,000 comparisons in the worst case (O(n)).
- Ask: "What if, instead of searching every shelf, we had a math formula that looked at the letters of a key and told us the exact shelf number in 1 step?"
- That is a Hash Table (called a
dict in Python or Map in JavaScript).
2. Direct instruction: Computing a Toy Hash Function & Modulo Indexing (15 min)
- Define a simple, hand-computable hash rule for a table with
M = 7 buckets numbered 0 through 6:
- Step A: Add the alphabet positions (
A=1, B=2, ..., Z=26) of the letters in the key (sum).
- Step B: Divide
sum by 7 and take the remainder:
bucket = sum mod 7 (the remainder is always 0, 1, 2, 3, 4, 5, or 6!).
- Work through 6 animal keys together on the board:
| Key |
Letter Values |
sum |
Division by 7 |
bucket = sum mod 7 |
"CAT" |
3 + 1 + 20 |
24 |
24 = 3 × 7 + 3 |
Bucket 3 |
"DOG" |
4 + 15 + 7 |
26 |
26 = 3 × 7 + 5 |
Bucket 5 |
"ANT" |
1 + 14 + 20 |
35 |
35 = 5 × 7 + 0 |
Bucket 0 |
"OWL" |
15 + 23 + 12 |
50 |
50 = 7 × 7 + 1 |
Bucket 1 |
"BEE" |
2 + 5 + 5 |
12 |
12 = 1 × 7 + 5 |
Bucket 5 (COLLISION with "DOG"!) |
"FOX" |
6 + 15 + 24 |
45 |
45 = 6 × 7 + 3 |
Bucket 3 (COLLISION with "CAT"!) |
- Show why Separate Chaining is essential:
- When
"BEE" lands in Bucket 5, we must not erase "DOG". Instead, Bucket 5 holds a short chain: Bucket 5 → [ ("DOG", val), ("BEE", val) ].
- When looking up
"BEE", the computer computes 12 mod 7 = 5, jumps straight to Bucket 5, checks "DOG" (not a match), and finds "BEE" on the 2nd comparison—still only 2 comparisons instead of scanning all 6 items!
3. Main activity: Pair Hash-Table Build & Worst-Case Adversarial Attack (17 min)
- Part A — Insert 3 More Keys (10 min):
Student pairs draw the 7-bucket table (
0..6) with the 6 animals above already placed, then compute and insert three more keys:
"ELK" (5 + 12 + 11 = 28; 28 mod 7 = 0 → chains after "ANT" in Bucket 0)
"HEN" (8 + 5 + 14 = 27; 27 mod 7 = 6 → lands in empty Bucket 6)
"COD" (3 + 15 + 4 = 22; 22 mod 7 = 1 → chains after "OWL" in Bucket 1)
- Part B — Count Comparisons & Load Factor (7 min):
- Total items
n = 9, total buckets M = 7 → Load factor α = 9 / 7 ≈ 1.29 items per bucket.
- What is the maximum number of key comparisons needed to find any of the 9 animals in our hash table? (Only 2 comparisons, because the longest chain has length 2!)
- Adversarial thought experiment: Why doesn't our hash function only check the first letter of a word? (Because in an English dictionary, thousands of words start with
'S', piling into one giant chain while 'X' is nearly empty!)
4. Discussion questions (5 min)
- Question 1: "Why must a hash function be 100% deterministic (never using a random number generator each time you look up a key)?"
- Example good answer: If
h("CAT") returned Bucket 3 when inserting and a random Bucket 6 when looking it up later, you would look in the wrong bucket and never find "CAT" again!
- Question 2: "What happens to lookup speed if we put
n = 7,000 items into only M = 7 buckets (α = 1,000)? How do real hash tables prevent that?"
- Example good answer: Each bucket chain would average
1,000 items long, slowing lookups back down to linear scans. Real hash tables resize (rehash)—doubling M whenever the load factor α = n / M passes a threshold like 0.75.
5. Closing check (5 min)
Using the same rule (letter sum mod 7, with A=1 ... Z=26):
- Compute the letter sum and bucket index (
0..6) for the key "BAT" (B=2, A=1, T=20).
- Does
"BAT" collide with any key in our 9-animal table from the lesson? If so, which bucket does it join, and which keys are already in that bucket?
- A hash table has
M = 50 buckets and currently stores n = 35 keys. What is its load factor α, and why is a low load factor desirable?
Worked answers for closing check
B(2) + A(1) + T(20) = 23. Dividing by 7 gives 23 = 3 × 7 + 2, so 23 mod 7 = 2 (Bucket 2).
- No collision! In our 9-animal table, Buckets
0, 1, 3, 5, 6 had items, while Bucket 2 and Bucket 4 were empty. So "BAT" is the first item in Bucket 2.
- Load factor
α = 35 / 50 = 0.70. A low load factor means most buckets have 0 or 1 item, keeping lookups close to 1 comparison (O(1)).
Differentiation
- Extra support: Provide a printed multiplication table for
7 (0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70) so students can find sum mod 7 immediately by subtracting the largest multiple of 7 at or below sum.
- Extra challenge: Have students find an anagram collision (such as
"ACT", "CAT", and "TAC"): why do all anagrams collide under an addition-only hash function, and how does multiplying each letter by a position weight (1×L1 + 31×L2 + 31²×L3) break anagram collisions?
Teacher notes
- Common misconception: Students often assume a hash collision means the hash table "failed" or overwrote the earlier key. Emphasize that collisions are normal and expected (by the Pigeonhole Principle / Birthday Paradox), and that separate chaining stores both keys safely in the same bucket list.