Data Structures · Hashing

Handling collisions in a hash table

A hash function sends every key to a slot, but sooner or later two keys want the same slot. This page explains why that is unavoidable, shows five standard ways to handle it with diagrams, and then lets you try each one live.

What is a collision?

A hash table stores key/value pairs in an array. A hash function turns each key into an index, so a lookup can go straight to the right slot in O(1) time instead of scanning the whole array in O(n).

There are far more possible keys than slots: every possible name, but only a few hundred array positions. So some different keys must end up with the same index. When a new key hashes to a slot that is already taken, that is a collision, and keys that share a slot are called synonyms. Even a very good hash function only makes collisions rare; it cannot prevent them.

keys John Smith Lisa Smith Sandra Dee hashfunction table slots 0 1John Smith 2 3Lisa Smith 4 Sandra Dee also hashes to 1: a collision
Two keys, one slot. John Smith is stored in slot 1. When Sandra Dee also hashes to 1, the table needs a rule for where she goes. The rest of this page is about those rules.

Every strategy below falls into one of two families:

The diagrams all use the same seven keys, 50, 700, 76, 85, 92, 73, 101, in a table of 7 slots with h(k) = k mod 7. Three of them (50, 85, 92) hash to slot 1, and two (73, 101) hash to slot 3.

Five ways to handle collisions

1. Separate chaining slot i holds a linked list

Each slot points to a linked list of every key that hashed there. Insert adds a node at the front of the list; search walks the list comparing keys. The table never fills up: it just gets longer lists.

With n keys in m slots, the average list has n / m nodes (the load factor α), so search takes O(1 + α) on average.

GoodSimple. Deletes are easy. Works even when α > 1.
CostsExtra memory for pointers. Following pointers is slower than scanning an array.
Chaining. 50, 85 and 92 all hash to 1 and share one list (newest first). 73 and 101 share slot 3.

2. Buckets with chaining a fixed-size bucket, then an overflow list

This is the design in the class HashBucketsWithChaining code. Each slot is a bucket that holds up to B entries in a small array. Only when the bucket is full do extra entries go into an overflow linked list.

Most keys are found in the fast, contiguous bucket, and the linked list is only used for unlucky slots. Databases and file systems use buckets like this because one bucket fits in one disk block.

GoodFewer pointers to follow. Bucket entries sit next to each other in memory.
CostsSpace is reserved for B entries in every slot, used or not.
Buckets of size B = 2. Slot 1's bucket fills with 50 and 85, so 92 goes into its overflow list.

3. Linear probing try h, h+1, h+2, …

Open addressing in its simplest form: if slot h is taken, try the next slot, wrapping around at the end. Search follows the same sequence and stops at the key or at an empty slot.

probe(i) = (h(k) + i) mod m

The weakness is primary clustering: occupied slots form runs, any key that lands in a run has to walk to its end, and that makes the run longer still.

GoodVery simple. Probes touch neighboring memory, which is fast.
CostsClusters grow fast as α rises. Deletes need tombstones.
Linear probing. The badges show how 101 was placed: its home slot 3 is taken, then 4, so it lands in 5. Slots 0 to 6 have become one long cluster.

4. Quadratic probing try h, h+1, h+4, h+9, …

Instead of stepping one slot at a time, jump by successive squares. Keys that collide spread out quickly instead of piling into one run.

probe(i) = (h(k) + i²) mod m

This removes primary clustering. Keys with the same home slot still follow the same path (secondary clustering). The probe sequence does not visit every slot: if m is prime and the table is at most half full, a free slot is always found; past that, an insert can fail even though empty slots remain.

GoodBreaks up clusters. Still cheap to compute.
CostsKeep m prime and α ≤ 0.5 to be safe.
Quadratic probing. 101 starts at 3 (taken), then tries 3 + 1 = 4, which is free.

5. Rehashing (double hashing) step size from a second hash

On a collision, apply a different hash function to decide where to go next. The usual form is double hashing: a second hash function h₂ gives each key its own step size.

probe(i) = (h(k) + i · h₂(k)) mod m,   h₂(k) = R − (k mod R)

R is a prime smaller than m (here R = 5), and h₂ is never 0. Two keys with the same home slot usually have different step sizes, so they follow different paths. That removes secondary clustering too.

"Rehashing" also names something else: when a table gets too full, allocate a bigger array and re-insert every key. Both ideas matter; this section is about the first.

GoodThe fewest collisions of the open-addressing methods.
CostsTwo hash computations. Probes jump around memory.
Double hashing. For 101, h₂ = 5 − (101 mod 5) = 4. It tries 3, 0, 4, 1, 5 (all taken) and lands in 2.

Comparing the five

StrategyWhere colliding keys goCan α exceed 1?ClusteringDeleting
Separate chainingA linked list in the same slotYesNone; long lists insteadUnlink the node
Buckets with chainingThe bucket, then an overflow listYesNone; overflow lists insteadRemove from bucket or list
Linear probingThe next free slotNoPrimary (long runs)Leave a tombstone
Quadratic probingSlots h + 1, 4, 9, …No (keep α ≤ 0.5)Secondary onlyLeave a tombstone
Double hashingSlots h + i · h₂(k)NoVery littleLeave a tombstone

Try each one

Pick a strategy, then insert, search for or delete keys. Keys can be whole numbers (hashed as k mod m) or words (hashed with the djb2 string hash from the class code). The probe badges show the order in which slots were checked.

The table

What is happening

Calls

    C++

      Compare all five on the same keys

      This inserts one list of keys into each strategy at once and measures the result. "Average probes" is how many slots or nodes a successful search looks at, averaged over every key.