16. Hash Tables & Collision Resolution

Map keys to slots — and what happens when two keys want the same one

You look up a word in a dictionary, a username in a database, a cached web page by its URL. In every case, you want the same thing: given a key, find its value — instantly. Not in O(log n) time like a binary search tree. In O(1) time. Constant time.

Hash tables make this possible. They're the single most widely used data structure in practical programming — behind every Python dict, every JavaScript object, every Java HashMap, and every database index. The idea is beautifully simple: compute a function of the key that tells you exactly where to store it.

The Core Idea

A hash table is an array of m slots (called buckets). To store a key-value pair, you compute:

index = hash(key) % m

Then you put the value at table[index]. To look it up later, compute the same hash, go to the same index, and there it is. No searching, no comparisons — just one computation and one array access.

Why O(1)?

Array access by index is constant time. If the hash function takes constant time to compute, the entire lookup is O(1) — regardless of how many elements are in the table.

What a Hash Function Does

A hash function takes an arbitrary key (a string, number, object) and returns a fixed-size integer. A good hash function has three properties:

Property What it means Why it matters
Deterministic Same key always produces the same hash You must be able to find what you stored
Uniform distribution Outputs are spread evenly across all possible values Minimizes collisions — keys don't cluster in the same slots
Avalanche effect A tiny change in input drastically changes the output Similar keys (like "cat" and "cats") land in different slots

A Simple Example

Let's store some names in a hash table of size 7. We'll use a simple hash: sum the ASCII values of each character, then take mod 7.

Hashing names into a table of size 7

hash("Alice") = (65+108+105+99+101) % 7 = 478 % 7 = 2
hash("Bob")   = (66+111+98)         % 7 = 275 % 7 = 2
hash("Carol") = (67+97+114+111+108) % 7 = 497 % 7 = 0
hash("Dave")  = (68+97+118+101)     % 7 = 384 % 7 = 6
hash("Eve")   = (69+118+101)        % 7 = 288 % 7 = 1

Slot: [0] [1] [2] [3] [4] [5] [6] Carol Eve Alice,Bob — — — Dave

Alice and Bob both hash to slot 2. That's a collision — and we need a strategy to handle it.

The Birthday Problem: Collisions Are Inevitable

You might think: "Just use a bigger table or a better hash function, and collisions will go away." They won't. This is the birthday problem in disguise.

The Birthday Paradox

In a room of just 23 people, there's a >50% chance two share a birthday (out of 365 possibilities). Similarly, with a table of m slots, a collision becomes likely after inserting only about √m keys. For a table with 1,000,000 slots, expect your first collision around key 1,177.

No hash function can avoid collisions when the space of possible keys is larger than the number of slots (and it always is). So every hash table implementation must have a collision resolution strategy.

Collision Resolution 1: Chaining

The simplest approach: each slot holds a linked list (or any dynamic collection). When two keys hash to the same slot, just append to the list.

  1. Insert

    Compute index = hash(key) % m. Append (key, value) to the list at table[index].

  2. Lookup

    Compute the index. Walk the list at that slot, comparing keys until you find a match (or reach the end).

  3. Delete

    Find the key in the list and remove the node. Standard linked-list deletion.

Chaining: inserting Alice, Bob, Carol, Dave, Eve (table size 7)

Slot 0: [Carol] →
Slot 1: [Eve] →
Slot 2: [Alice] → [Bob] →
Slot 3: (empty)
Slot 4: (empty)
Slot 5: (empty)
Slot 6: [Dave] →

To find Bob:

  1. hash("Bob") % 7 = 2
  2. Go to slot 2 → first node is Alice (not Bob)
  3. Follow link → next node is Bob ✓ found!

Collision Resolution 2: Open Addressing

Instead of building chains, open addressing stores everything directly in the array. When a collision occurs, you probe for the next available slot using a deterministic sequence. There are three common probing strategies:

Linear Probing

Try index, then index+1, index+2, and so on (wrapping around). Simple, cache-friendly, but suffers from primary clustering — long runs of occupied slots tend to grow.

Linear probing: inserting Alice, Bob, Carol, Dave, Eve (table size 7)

Insert Alice: hash = 2, slot 2 is empty → place at slot 2
Insert Bob:   hash = 2, slot 2 is occupied → try 3, empty → place at slot 3
Insert Carol: hash = 0, slot 0 is empty → place at slot 0
Insert Dave:  hash = 6, slot 6 is empty → place at slot 6
Insert Eve:   hash = 1, slot 1 is empty → place at slot 1

Slot: [0] [1] [2] [3] [4] [5] [6] Carol Eve Alice Bob — — Dave

To find Bob:

  1. hash("Bob") % 7 = 2
  2. Slot 2 = Alice (not Bob) → probe to slot 3
  3. Slot 3 = Bob ✓ found! (probe sequence length: 2)

Quadratic Probing

Try index, index + 1², index + 2², index + 3², etc. Spreads out the probes to reduce clustering, but can miss slots if the table size isn't chosen carefully (prime sizes work best).

Double Hashing

Use a second hash function to determine the step size: probe(i) = (h1(key) + i × h2(key)) % m. This eliminates clustering almost entirely, at the cost of computing two hash functions.

Load Factor

The load factor α = n/m (number of elements divided by table size) is the single most important metric for hash table performance.

Strategy Expected lookup cost What happens as α grows
Chaining O(1 + α) Graceful degradation — chains get longer but table never "fills up." α can exceed 1.
Open addressing O(1 / (1 - α)) Dramatic degradation near full. At α = 0.9, expect ~10 probes per lookup. At α = 1.0, infinite loop.

The Sweet Spot

Most implementations keep α between 0.5 and 0.75. Java's HashMap resizes at α = 0.75. Python's dict resizes at α ≈ 0.67. This keeps the expected number of probes or chain length small — typically under 2.

Resizing (Rehashing)

When the load factor exceeds the threshold, the table needs to grow. The process:

  1. Allocate a new, larger array

    Typically double the size (then round up to the next prime for better distribution).

  2. Rehash every existing key

    You can't just copy entries — hash(key) % new_size gives different indices than hash(key) % old_size. Every key must be reinserted.

  3. Replace the old table

    Swap the pointer and free the old array. The O(n) rehash cost is amortized across all the insertions that filled the table, so the amortized cost per insert remains O(1).

Good Hash Functions

The choice of hash function matters enormously. Here are three widely used approaches:

1. Modular hashing with primes

hash(key) = key % p    (where p is a prime)

Why primes? If the table size is a prime number, the modulo distributes keys more uniformly — patterns in the input data don't create patterns in the slot assignments.

2. Multiplication method (Knuth)

hash(key) = floor(m * ((key * A) mod 1))

where A ≈ 0.6180339887 (the golden ratio conjugate)

This works well regardless of table size and produces a good distribution even for sequential keys.

3. FNV-1a (for strings and byte sequences)

hash = 2166136261            // FNV offset basis
for each byte in key:
    hash = hash XOR byte
    hash = hash * 16777619   // FNV prime

Fast, simple, good avalanche properties. Used in many hash table implementations.

Chaining vs Open Addressing

AspectChainingOpen Addressing
Collision handling Linked list at each slot Probe for next empty slot
Memory layout Scattered (pointer chasing) Contiguous (cache-friendly)
Load factor Can exceed 1.0 Must stay below 1.0 (typically ≤ 0.75)
Deletion Simple — remove from list Tricky — need tombstone markers
Worst-case clustering No clustering Primary/secondary clustering possible
Extra memory Pointer overhead per node None — entries live in the array
Best for Unknown or variable load, frequent deletes Known size, read-heavy workloads, cache performance

Complexity

Operation Average case Worst case
Insert O(1) O(n)
Lookup O(1) O(n)
Delete O(1) O(n)
Space O(n) O(n)

The O(n) worst case happens when all keys hash to the same slot — every lookup becomes a linear scan. This is why a good hash function and a sensible load factor are essential. In practice, with a reasonable hash function, you'll almost never see worse than O(1).

Where Hash Tables Are Used

Application How it uses hash tables
Dictionaries / Maps Python dict, Java HashMap, Go map, JS objects — all hash tables under the hood
Sets A hash table storing only keys (no values). O(1) membership test.
Database indexes Hash indexes for exact-match queries. PostgreSQL, MySQL, Redis all use them.
Caches Memcached and Redis map cache keys to values via hashing
Symbol tables Compilers map variable names to their types, scopes, and memory locations
Deduplication Insert items into a set — duplicates hash to the same entry and are ignored
Counting / frequency Map each item to its count. The classic "word frequency" problem.

Key Takeaways

  • Hash tables map keys to array indices via hash(key) % table_size, giving O(1) average-case lookups
  • A good hash function is deterministic, distributes uniformly, and has the avalanche effect
  • Collisions are mathematically inevitable (birthday problem) — every hash table needs a collision strategy
  • Chaining stores collisions in linked lists; open addressing probes for empty slots in the array
  • The load factor α = n/m controls performance — keep it below 0.75 and resize when it gets too high
  • Resizing requires rehashing every key into the new array, but the amortized cost per insert stays O(1)
  • Hash tables are the backbone of dictionaries, sets, caches, database indexes, and countless other systems

Try It Yourself — Hash Table Simulator

Choose a table size and collision strategy, then insert keys to watch them hash into slots. See how collisions are resolved in real time.

Insert a key to begin.

Table Visualization

0
Items stored
0.00
Load factor (α)
0
Collisions
0
Longest chain / probe

Hash tables are the workhorse of computer science — the structure you reach for whenever you need fast lookups by key. Understanding how they work under the hood, especially how they handle collisions and when they need to resize, will make you a better programmer in every language you use.