Collisions, worst cases and mutable keys
Bad keys can pile into one bucket and turn a hash table into a slow list. Mutable keys can get lost after they change.
Before you start: Hash sets and maps in practice: counting, lookup, deduplication.
The idea
Someone sends only multiples of 8. Every key lands in bucket 0, and the table turns into one long list.
In 2011 web servers in many languages were knocked out this way. Attackers posted form fields whose names all hashed to one bucket.
Intuition
Ordinary keys spread out. Six keys use six different buckets, so each lookup checks one key.
The O(1) promise is an average. It holds only when the hash spreads keys evenly over the buckets.
Strings can collide too. A hash that adds letter codes gives abc, bca, cab and acb the same sum, 294.
A weak hash ignores some part of the key, here the letter order. Every key that differs only in that part collides.
Complexity
Spread-out keys cost about one comparison per search. Keys in one bucket cost n comparisons, the same as a list.
The average case is O(1) and the worst case is O(n) per operation. n inserts into one bucket cost O(n²) in total.
Variations
Python and Rust mix a random secret seed into string hashes. Attackers cannot predict buckets, so they cannot aim keys.
The seed is chosen when the program starts. The same key lands in different buckets in different runs.
Java's HashMap turns a chain of 8 or more keys into a balanced tree. A flooded bucket then costs O(log n), not O(n).
Code
Pseudocode
put(key)
i ← hash(key) mod m
if key not in bucket[i]: append key // scans the whole chain
get(key)
i ← hash(key) mod m
for each k in bucket[i]
if k = key: return found
return not found
Python
def put(table, key):
i = hash(key) % len(table)
if key not in table[i]:
table[i].append(key)
def get(table, key):
i = hash(key) % len(table)
for k in table[i]:
if k == key:
return True
return False
JavaScript
function put(table, key) {
const i = hash(key) % table.length;
if (!table[i].includes(key)) table[i].push(key);
}
function get(table, key) {
const i = hash(key) % table.length;
for (const k of table[i]) {
if (k === key) return true;
}
return false;
}
Practice problems (3)
Identify the bad keys Warm-up
A table has 8 buckets and uses key mod 8 as its hash. Which set of keys turns it into one long chain?
Predict degraded complexity Standard
A table has 8 buckets and uses key mod 8. An insert first scans its chain for a duplicate. Insert 8, 16, 24, 32, 40, then search for 40. Answer each question before the step plays.
Spot the bug: mutable key Standard
A robot starts at (0, 0) and follows moves, a string of U, D, L and R steps. This function should return true when the robot stands on some point twice, counting the start. It is wrong for some inputs. Click the line with the bug, then fix it.
Next on the path: Recursion: base case, recursive case, the call stack