Chapter 17 · Hashing

Collision Resolution

A collision occurs when two different keys hash to the same bucket index. Since any hash table has finite slots and infinite possible keys, collisions are unavoidable. Two families of strategies handle them: separate chaining (multiple keys per bucket) and open addressing (find another slot).

How do hash tables handle collisions?

A collision happens when two keys hash to the same bucket. Separate chaining stores a small list in each bucket and appends colliding entries to it. Open addressing stores everything in the array itself and probes for the next free slot (linear probing, quadratic probing or double hashing). Both keep lookups O(1) on average as long as the table doesn't get too full.

// Separate chaining
const buckets = Array.from({ length: 8 }, () => []);
function set(key, value) {
  const bucket = buckets[hash(key) % buckets.length];
  const entry = bucket.find((e) => e[0] === key);
  entry ? (entry[1] = value) : bucket.push([key, value]);
}

Live demo — watch collisions happen

Add keys and watch the hash function assign them to buckets. When two keys map to the same bucket, that is a collision — exactly what the strategies below resolve.

Hash Map — 8 buckets · h(k) = polyHash(k) % 8

entries: 0
[0]
—
[1]
—
[2]
—
[3]
—
[4]
—
[5]
—
[6]
—
[7]
—

Separate chaining

Each bucket holds a linked list (or dynamic array). Multiple keys can share a bucket. Never needs rehashing as urgently — chains just grow longer.

0bucketnull
1bucket
alice→carol→ null
2bucketnull
3bucket
bob→ null
4bucket
dave→eve→frank→ null
5bucketnull
chaining-get.pseudo
1get(key):
2 idx <- hash(key) mod m
3 chain <- buckets[idx] // linked list at this bucket
4 for each node in chain:
5 if node.key == key: return node.value
6 return NULL // not found

Open addressing

All keys are stored directly in the array. When a collision occurs, probe for the next available slot using a probe sequence. Three probe strategies:

Linear probing

probe(i) = (hash(key) + i) mod m

+ Excellent cache performance — sequential memory access

− Primary clustering: long runs of filled slots form, increasing collisions

Quadratic probing

probe(i) = (hash(key) + i²) mod m

+ Avoids primary clustering — jumps skip over filled regions

− Secondary clustering: same hash = same probe sequence. May not visit all slots.

Double hashing

probe(i) = (hash1(key) + i * hash2(key)) mod m

+ Nearly uniform distribution — different h2 values = different sequences

− Two hash computations per probe; hash2 must be non-zero and coprime to m

open-addressing-get.pseudo
1get(key): // linear probing example
2 i <- 0
3 idx <- hash(key) mod m
4 while buckets[idx] != EMPTY and i < m:
5 if buckets[idx].key == key:
6 return buckets[idx].value
7 i <- i + 1
8 idx <- (hash(key) + i) mod m // linear probe step
9 return NULL // not found
10 
11remove(key): // mark DELETED, not EMPTY
12 // Open addressing requires a tombstone marker for deleted slots.
13 // If we mark as EMPTY, future lookups break (chain is interrupted).
14 buckets[idx] <- DELETED // probe sequence continues past this

Load factor & rehashing

load factor α = n / m    (n = items, m = buckets)

α=0.0 – 0.5

Chaining: fast, low collision. Open addressing: good.

α=0.5 – 0.7

Chaining: acceptable. Open addressing: getting slow (recommended max ~0.7).

α=0.7 – 1.0

Chaining: slow chains. Open addressing: many probes, approaching O(n).

α=> 1.0

Only possible with chaining. Very slow — many long chains.

💡When to rehash
Rehashing doubles the array size and re-inserts every key. Java HashMap rehashes when load factor exceeds 0.75. Python's dict rehashes at 2/3. The amortized cost is O(1) per insert because each rehash doubles capacity, so each element is moved on average only once per O(n) inserts.

Chaining vs Open Addressing

AspectSeparate ChainingOpen Addressing
Memory layoutScattered (pointer chasing)Contiguous array
Cache behaviorPoor (pointer indirection)Excellent (sequential)
Max load factorCan exceed 1.0Must stay below 1.0
Delete complexitySimple removal from listRequires tombstone markers
ClusteringNonePrimary (linear), secondary (quadratic)
Best forMany collisions, unknown sizeCache-sensitive, bounded size

Time complexity

get, put, remove — average with good hash function and low load factorO(1)

Constant time

get, put, remove — worst case (all keys in same bucket)O(n)

Linear time

rehash — O(n) work but amortized O(1) per insertO(n)

Linear time

🎯 Quick Check

When using open addressing and you delete a key, why must you mark it as DELETED (tombstone) rather than EMPTY?

Collision Resolution: summary

Key points

  • Load factor = entries ÷ buckets. Tables resize (often at about 0.75) to keep chains short.
  • Linear probing is cache-friendly but suffers from clustering.
  • Deleting in open addressing needs tombstones so later lookups don't stop early.

Frequently asked questions

›Chaining or open addressing?

Chaining is simpler and tolerates high load factors. Open addressing uses memory more efficiently and is faster in practice when the table is kept sparse.