Hash Functions
A hash function maps any key to a fixed-size index in O(key length) time. Done right, it gives O(1) average-case for insert, lookup, and delete — the foundation of hash maps, sets, caches, Bloom filters, and checksums.
What is a hash function?
A hash function turns a key (such as a string) into a number, which a hash table uses as an array index. A good hash function is fast, deterministic (the same key always gives the same number) and spreads keys evenly so few of them collide. Cryptographic hashes like SHA-256 add security properties, but hash tables need speed and even distribution.
function hash(key, buckets) { // simple string hash (djb2-style)
let h = 5381;
for (const ch of key) h = (h * 33 + ch.charCodeAt(0)) >>> 0;
return h % buckets;
}
hash("apple", 16); // always the same bucket for "apple"Collision chaining — animated
// Array state
// Pseudocode
Live demo — hash and insert
Type any key and see which bucket the polynomial rolling hash selects. Add multiple keys to see the distribution and spot collisions.
Hash Map — 8 buckets · h(k) = polyHash(k) % 8
entries: 0Bucket memory layout
Bucket array after inserting cat, act, dog — bucket 5 chains
Design principles
What makes a good hash function?
1. Deterministic — same key always gives same hash. 2. Uniform distribution — keys spread evenly across buckets. 3. Fast — O(n) of key length. 4. Avalanche — small key change causes large hash change.
Polynomial rolling hash
1// Polynomial rolling hash — O(n)2function polyHash(key, tableSize):3 BASE = 31 // small prime (a-z)4 PRIME = 1_000_003 // large prime for mod5 h = 06 for ch in key:7 h = (h * BASE + charCode(ch)) % PRIME8 return h % tableSize // map to bucket index910// Example: hash('cat', 10)11// c=99, a=97, t=11612// h = ((99*31 + 97)*31 + 116) % 1_000_003 % 10
Insert with chaining + resize
1// Hash map insert with chaining2function insert(map, key, value):3 idx = polyHash(key, map.capacity)4 bucket = map.buckets[idx] // linked list5 for node in bucket:6 if node.key == key:7 node.value = value // update existing8 return9 bucket.append({key, value}) // new entry1011// Resize when load factor > 0.712function resize(map):13 newMap = HashMap(map.capacity * 2)14 for every (key, value) in map:15 insert(newMap, key, value) // re-hash all16 return newMap
Complexity
O(k) time
Constant time
Linear time
Linear time
🎯 Quick Check
What is the primary purpose of a large prime modulus P in polynomial rolling hash?
Hash Functions: summary
Key points
- Collisions are unavoidable (more possible keys than buckets); tables must handle them.
- Using a prime or power-of-two table size, with good mixing, spreads keys evenly.
- Never use a fast non-cryptographic hash for passwords; use bcrypt or Argon2.
Frequently asked questions
›What makes a good hash function?
It's fast, deterministic, and distributes keys uniformly so that similar keys land in very different buckets.