Core Primitive

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

7-bucket hash table — insert cat, act, dogstep 1/4

// Array state

_
[0]
_
[1]
_
[2]
_
[3]
_
[4]
cat
cat
_
[6]
→ Table size = 7. Insert 'cat': polyHash('cat',7) = 5. Place in bucket 5.

// Pseudocode

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 mod
5 h = 0
6 for ch in key:
7 h = (h * BASE + charCode(ch)) % PRIME
8 return h % tableSize // map to bucket index
9 
10// Example: hash('cat', 10)
11// c=99, a=97, t=116
12// h = ((99*31 + 97)*31 + 116) % 1_000_003 % 10

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: 0
[0]
—
[1]
—
[2]
—
[3]
—
[4]
—
[5]
—
[6]
—
[7]
—

Bucket memory layout

_0
_1
act2
_3
_4
cat → dog5
_6

Bucket array after inserting cat, act, dog — bucket 5 chains

Design principles

1 / 4
1

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.

1 of 4

Polynomial rolling hash

poly-hash.pseudo
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 mod
5 h = 0
6 for ch in key:
7 h = (h * BASE + charCode(ch)) % PRIME
8 return h % tableSize // map to bucket index
9 
10// Example: hash('cat', 10)
11// c=99, a=97, t=116
12// h = ((99*31 + 97)*31 + 116) % 1_000_003 % 10

Insert with chaining + resize

hash-map-insert.pseudo
1// Hash map insert with chaining
2function insert(map, key, value):
3 idx = polyHash(key, map.capacity)
4 bucket = map.buckets[idx] // linked list
5 for node in bucket:
6 if node.key == key:
7 node.value = value // update existing
8 return
9 bucket.append({key, value}) // new entry
10 
11// Resize when load factor > 0.7
12function resize(map):
13 newMap = HashMap(map.capacity * 2)
14 for every (key, value) in map:
15 insert(newMap, key, value) // re-hash all
16 return newMap

Complexity

Hash computation — O(key length k)O(k)

O(k) time

Insert / lookup / delete — average with load ≤ 0.7O(1)

Constant time

Resize — rehash all n entries, amortized O(1) per insertO(n)

Linear time

Worst case — all keys collide to one bucket (pathological)O(n)

Linear time

⚠️Hash DoS attacks
If an attacker can predict your hash function, they can craft inputs that all hash to the same bucket, causing O(n) lookups and crashing your server. Defend with hash randomization (salt your hash seed per process start). Python, Ruby, and Rust do this by default.
💡Open addressing vs chaining
Chaining: each bucket holds a linked list. Fast at high load, simple to implement. Open addressing (linear probe, quadratic probe, Robin Hood): store entries directly in the array. Better cache performance, but performance degrades fast above 80% load.

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