Fill a table to 90%. A lookup of a missing key then costs about 1.9 steps with chains, 10 probes with double hashing and 50.5 probes with linear probing.
Pick a strategy, set how full the table is, and press Search for a key that is not there. Watch the probes pile up. Then we build the table from zero, up to a table that never collides.
You need Python lists and the remainder operator %. We build the rest from zero.
Based on Chapter 11, "Hash Tables", of Introduction to Algorithms (CLRS) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). The explanations, toys and devices are our own.
A toy table of 53 slots with seeded random keys. The bars are measured on this table; the lede's numbers are the textbook averages for a large table.
Chapter 0
Compute where a key lives, then learn why two keys soon want the same place
A spell checker holds 100,000 words. You type a word, and it must say whether the word is in the list. A scan of an unsorted list can check all 100,000. Binary search on a sorted list checks about 17.
A hash table does better. A hash function turns the key into a slot number in an array. You compute the slot and look there once. The work does not grow with the size of the list.
The catch: two keys can get the same slot. That is a collision. Collisions come much sooner than you expect.
The curve is the chance of at least one collision after k keys. Move the slider, or press Throw to drop random keys until two share a slot.
The curve is exact for keys that land in uniformly random slots. Each trial is one random run.
How soon? Call the number of slots m and the number of keys k. Every pair of keys is a chance to collide, and each pair collides with chance 1 in m. Call the chance of at least one collision P.
P is about one minus e to the minus k times k minus one over two, divided by m.
Count the pairs of keys. Divide by m to get the expected number of collisions. P is one minus e to the minus that number.
m = 1,000 and k = 38. The pairs are 38 × 37 / 2 = 703. Then 703 / 1,000 = 0.703, and e−0.703 = 0.495. So P ≈ 0.505. The exact chance is 0.509, with the table under 4% full.
The same sum gives the famous birthday result: with 365 days, 23 people share a birthday with a chance over 50%.
Failure. Code stores one key per slot and never checks. A second key overwrites the first without a sign. Measure: insert n different keys, then read each one back and count the losses. Fix: give the table a collision rule, chaining or open addressing.
Chapter 1
Give every possible key its own slot, and pay for the slots you never use
Suppose every key is a whole number from 0 to m − 1. Make an array T of m slots and store key k in T[k]. That is a direct-address table. Insert, search and delete each touch one slot, and no two keys can collide.
pythonclass DirectAddressTable: def __init__(self, m): self.T = [None] * m # one slot per possible key: O(m) space def insert(self, k, value): self.T[k] = value # O(1) def search(self, k): return self.T[k] # None if absent def delete(self, k): self.T[k] = None
The set of all keys that could ever appear is the universe U. The array needs one slot for each key in U, not for each key you store. Call the number of stored keys n. When U is much larger than n, most slots stay empty.
Pick a kind of key. Each bar is a count of slots on a log scale, so one step right is ten times more.
Illustrative: 1,000 stored keys (all 26 for letters), 8 bytes per slot, and a hash table of 2n slots.
| Keys | Universe U | Direct table at 8 bytes a slot | Empty with 1,000 keys |
|---|---|---|---|
| Lowercase letters | 26 | 208 bytes | none, if all 26 appear |
| Port numbers | 65,536 | 524 KB | 98.5% |
| 9-digit IDs | 1,000,000,000 | 8 GB | 99.9999% |
| IPv6 addresses | 3.4 × 1038 | impossible | all but a vanishing fraction |
A hash table keeps the one-step lookup and drops the waste. It maps the huge universe onto m slots, with m close to n. The price is that two keys can now share a slot.
Failure. A service keys an array by user ID and runs out of memory with only a thousand users. Measure: compare the array length with the count of stored keys. Fix: if U is far larger than n, hash the keys.
Chapter 2
Turn any key into a slot number, and spread the keys evenly
A hash function h maps each key k to a slot h(k) from 0 to m − 1. It must be deterministic: the same key always gives the same slot. A good one also spreads the keys evenly over the slots.
The division method takes the remainder: h(k) = k mod m. It costs one division. Its trap is m. If m is a power of 2, k mod m keeps only the low bits of k. Memory addresses are often multiples of 8, so their low three bits are always zero.
A string becomes a number first. Treat each character code as a digit in base 128: "cat" is 99 × 1282 + 97 × 128 + 116 = 1,634,548.
Each bar is one slot; its height is the number of keys in it. Try multiples of 8 with 32 slots and the division method.
The keys are 0, 8, 16, …, 792, or 100 seeded random numbers below 10,000.
The multiplication method works for any m. Call the key k, the table size m, and a fixed constant A between 0 and 1. The fractional part of a number is what is left after you drop its whole part: the fractional part of 25.957 is 0.957.
h of k equals the floor of m times, k A mod one.
Multiply the key k by A. Keep only the fractional part. Multiply that by m and round down. The result is the slot.
k = 123,456, m = 1,024, A = 0.6180339887. Then k A = 76,300.0041, whose fractional part is 0.0041. Times 1,024 that is 4.21, so h(k) = 4.
Hash the keys 42, 130 and 77 into m = 11 slots. Division gives 9, 9 and 0, so 42 and 130 collide. Multiplication gives 10, 3 and 6. Neither method wins on every key set; that is the job of the next chapter.
Failure. A table of 1,024 slots holds pointers. The load is 1 key per slot, yet some chains hold 8 keys. Measure: count the keys in each slot and plot the counts. Fix: use a prime m far from a power of 2, such as 1,021, or the multiplication method.
Chapter 3
Choose the hash function at random, so no input can be bad on purpose
Every fixed hash function has bad inputs. If an attacker knows h, they can send keys that all land in one slot. Each lookup then walks one long chain of n keys. In 2011, crafted web requests did this to servers in PHP, Java, Python and Ruby.
Universal hashing picks the function at random when the program starts, from a family of functions. A family is universal if, for any two different keys, at most a fraction 1/m of its functions make them collide. The attacker cannot aim at a function they do not know.
CLRS gives one family. Pick a prime p larger than every key. Pick a at random from 1 to p − 1 and b from 0 to p − 1. Each pair (a, b) is one function in the family.
h sub a b of k equals a times k plus b, mod p, then mod m.
Multiply k by a and add b. Take the remainder after dividing by p. Take the remainder of that after dividing by m. The order matters: mod p first.
p = 17, m = 5, a = 3, b = 7. Key 4: 3 × 4 + 7 = 19, 19 mod 17 = 2, 2 mod 5 = 2. Key 0: 7 mod 17 = 7, 7 mod 5 = 2. They collide here. Over all 16 × 17 = 272 functions, keys 0 and 4 collide in 42 of them: 15.4%, under the promise of 1/5 = 20%.
The keys 8, 16, …, 96 go into 8 slots. Division puts them all in slot 0. Switch to Universal and draw new functions.
Toy keys. Over all 10,100 functions with p = 101, the longest chain averages 2.77.
Some draws are still bad: 26 of the 10,100 functions put all twelve keys in one slot. The promise is about the random draw. An attacker who does not know (a, b) cannot pick keys that hit one of those 26.
Failure. One endpoint takes seconds per request during a burst of odd keys. Measure: log the longest chain next to the load factor; a longest chain near n means an attack. Fix: a keyed hash with a secret seed, such as SipHash, which Python uses since version 3.4.
Chapter 4
Hang a list from each slot, and measure cost by how full the table is
Chaining keeps all the keys of one slot in a linked list, the slot's chain. Insert puts the new key at the head of its chain in one step. Search walks the chain at h(k). Delete finds the node and unlinks it.
Insert 5, 28, 19, 15, 20, 33, 12, 17, 10, 0 into m = 7 slots with h(k) = k mod 7. Slot 5 gets four keys and reads [12, 33, 19, 5], newest first. Slots 2 and 4 stay empty.
Each column is a slot; its chain grows down. Step inserts the next key of the example. Change m to rehash the same keys.
The first ten keys are the worked example. Random keys are below 100.
How long is a chain? Call the number of stored keys n and the number of slots m. The load factor is α = n/m, the average chain length. Assume simple uniform hashing: each key lands in any slot with the same chance, whatever the other keys do.
C miss equals one plus alpha.
Compute the slot. Check every key in its chain, because the missing key could be at the end. The average chain holds α keys.
The example: n = 10, m = 7, so α = 1.43 and Cmiss = 2.43. The chains hold 2, 1, 0, 2, 0, 4 and 1 keys; their average over the 7 slots is 10/7 = 1.43, the same α. A miss in slot 5 costs 1 + 4 = 5.
A hit stops at its key. CLRS shows it checks 1 + α/2 − α/(2n) keys on average: 1.64 here. This table's real average is 1.8 keys, because slot 5 is unlucky. Both costs stay constant while α stays constant, so grow m as n grows (Chapter 7).
Failure. Lookups get slower as the data grows, with no change in code. Measure: log n and m; at α = 10, each miss walks 10 nodes. Fix: resize when α passes about 1.
Chapter 5
Keep every key in the array, and try slots in a fixed order until one is free
Chains cost a pointer per key and jump around memory. Open addressing stores every key in the array itself. On a collision, the key tries other slots in a fixed order, its probe sequence, until one is free. Each try is a probe.
| Sequence | Probe i goes to | Weakness |
|---|---|---|
| Linear probing | (h′(k) + i) mod m | Primary clustering: runs of full slots grow, and every key that lands in a run walks to its end. |
| Quadratic probing | (h′(k) + c1i + c2i2) mod m | Keys with the same home slot follow the same path. |
| Double hashing | (h1(k) + i · h2(k)) mod m | Close to ideal. h2(k) must never be 0. |
Double hashing uses two hash functions. h1 gives the home slot, the first slot tried. h2 gives the step size. i counts the probes from 0.
h of k and i equals h one of k plus i times h two of k, mod m.
Start at the home slot h1(k). After each full slot, jump h2(k) slots further and wrap at the end. Stop at the first free slot.
m = 11, key 59: h1 = 59 mod 11 = 4 and h2 = 1 + 9 = 10. Probes go to 4, then (4 + 10) mod 11 = 3, then (4 + 20) mod 11 = 2. In the double-hashed table, 4 and 3 are full, so 59 lands in slot 2 after 3 probes.
Now insert 10, 22, 31, 4, 15, 28, 17, 88, 59 into m = 11 slots both ways. Linear probing builds a run from slot 4 to slot 7, and 59 walks 4, 5, 6, 7, 8: five probes.
Step inserts the next key and draws its probes. When all nine are in, delete a key on 59's path, then search for 59.
The keys are the worked example. Probe counts are exact.
Delete is the trap. If you empty a slot, a key that probed past it is lost: search stops at the first empty slot and says "not found". Mark the slot with a tombstone instead. Search walks past a tombstone; insert may reuse it.
Failure. After some deletes, lookups of keys that are still stored return "not found". Measure: search for every stored key and count the misses. Fix: tombstones, and a full rebuild when tombstones pile up.
Chapter 6
Derive the probe count from the load factor, and see where linear probing breaks
Assume uniform hashing: each key's probe sequence is equally likely to be any order of the m slots. In an open-address table, the load factor α = n/m is below 1, and it is the fraction of full slots.
Count the probes of a miss. The first probe always happens. A second happens only if the first slot was full: chance α. A third needs two full slots in a row: chance at most α2. So the probes add up to 1 + α + α2 + …
The expected number of probes is at most one over one minus alpha.
Each probe finds a full slot with chance α, so you need another. Add 1 + α + α2 and so on. That sum is 1 over 1 − α.
At α = 0.5 a miss takes 1/0.5 = 2 probes. At α = 0.9 it takes 1/0.1 = 10. The last 40% of filling makes a miss five times dearer.
Linear probing does worse, because full slots bunch into runs. Knuth worked out its average in 1963. Call the average probes of a miss under linear probing Elin.
E lin is about one half of, one plus one over one minus alpha, squared.
Take 1 − α and square it. Divide 1 by that. Add 1 and halve. Compare with double hashing, where 1 − α is not squared.
At α = 0.5: 1 − α = 0.5, squared 0.25, inverted 4, plus 1 is 5, halved 2.5. At α = 0.9: 0.01, then 100, then 101, then 50.5 probes, five times double hashing's 10.
Lines are the formulas. Drag the load, switch between misses and hits, and press Run to measure a real table of 1,009 slots.
Dots come from one seeded run with random keys. Chaining counts the hash step plus keys checked; open addressing counts probes.
| α | Chaining miss | Double hashing miss | Linear miss | Double hashing hit |
|---|---|---|---|---|
| 0.50 | 1.5 | 2 | 2.5 | 1.39 |
| 0.75 | 1.75 | 4 | 8.5 | 1.85 |
| 0.90 | 1.9 | 10 | 50.5 | 2.56 |
A hit costs less than a miss. It follows the path its key took when it went in, and the table was emptier then. CLRS bounds it by (1/α) ln(1/(1 − α)): 1.39 probes at α = 0.5.
Failure. An open-address table creeps to 95% full, and misses cost 200 probes under linear probing. Measure: export α and the average probe count as live metrics. Fix: resize when α passes 0.5 to 0.75.
Chapter 7
Double the array when it gets full, and see why the average insert stays cheap
Every cost so far depends on α, not on n. So keep α bounded: when α passes a threshold, make a new array twice as large and reinsert every key. Each key's slot depends on m, so every key moves. This is a rehash.
One rehash costs n moves. It is also rare. After a doubling, the next rehash waits until the key count doubles too. The amortized cost is the average cost per insert over a long run.
Start with 8 slots, grow at α = 0.75, and insert 100 keys. The rehashes happen when the table holds 6, 12, 24, 48 and 96 keys.
Each rehash moves half as many keys as the next one, so the sum never reaches twice the last rehash. That makes the total under 3n for any n. CLRS Chapter 17 proves this with a bank account: charge 3 per insert, spend 1, save 2 for the next rehash.
The step line is the total work so far; each jump is a rehash. The dashed line is 3n. Switch the growth rule.
Cost model: 1 per insert plus 1 per key moved. Start at 8 slots, grow when α would pass 0.75.
Failure. A table grows by a fixed 8 slots. Inserting 1,000 keys costs 84,166 steps, 84 per insert, against 2,530 with doubling. Measure: time n inserts for growing n; a curve that bends up means quadratic growth. Fix: grow by a factor, such as 2.
Chapter 8
Build a two-level table with no collisions at all, for a set that never changes
Expected O(1) is an average, not a promise for each lookup. For a static set, one that is fixed once built, we can promise it. Examples are the keywords of a language and the country codes. Perfect hashing builds a table where no two keys of the set collide.
The FKS scheme has two levels. Level 1 hashes the n keys into m = n slots with a universal function. Call the number of keys in slot j nj. Level 2 gives slot j its own table of nj2 cells and its own universal function. That function is redrawn until no two of the slot's keys collide.
Why nj2 cells? Call the number of colliding pairs in slot j's table X. There are nj(nj − 1)/2 pairs, and each collides with chance at most 1/nj2.
The expected X is at most n j times n j minus one, over two, times one over n j squared, which is less than one half.
Count the pairs in the slot. Multiply by each pair's chance to collide. The result is under a half, so at least half of all draws give no collision. Redraw until one works: about two tries.
nj = 4: 4 × 3 / 2 = 6 pairs, each with chance 1/16. E[X] = 6/16 = 0.375. So at least 62.5% of the draws are perfect.
The space stays linear. CLRS shows the expected total of all nj2 is under 2n when m = n. If a level-1 draw gives a total over 4n, redraw it; that happens with chance under a half.
Top row: the 10 level-1 slots and their counts. Under each slot: its square level-2 table, with each key in its own cell. Press Build to draw new functions.
Toy set: the ten keys of Chapter 4, p = 101. Tries count the level-2 draws for each slot.
Failure. Someone adds a key to a perfect table, and it collides or overwrites. Measure: check that the key set is truly fixed; count keys per level-2 cell. Fix: rebuild on every change, or use an ordinary table for a set that changes.
Chapter 9
See which textbook ideas the real tables use, and the tricks they add
| Table | Collisions | Grows at | Its trick |
|---|---|---|---|
Python dict | Open addressing; the next slot is 5j + 1 + perturb, where perturb starts as the full hash and shifts right 5 bits each probe | 2/3 full | Since 3.6, a dense entry array plus a small index array; it keeps insertion order |
Java HashMap | Chaining | 0.75 | A chain longer than 8 becomes a red-black tree, once the table has 64 slots |
C++ unordered_map | Chaining | 1.0 by default | Buckets you can inspect |
Swiss Table (Abseil), Rust HashMap | Open addressing | 7/8 full | One metadata byte per slot; SIMD checks 16 slots at once |
Why 8 in Java? The source code notes that, at its load, chain lengths follow a Poisson law with mean about 0.5. A chain of 8 then has chance about 0.00000006. The tree is a guard against bad hash codes and attacks, not a common case.
Robin Hood hashing (Celis, Larson and Munro, 1985) is linear probing with one rule. On insert, compare each resident's distance from its home slot with the new key's. If the new key is farther from home, they swap, and the evicted key probes on. The average distance stays the same; the longest one shrinks.
Both rows hold the same 11 keys in 13 slots. The bar over each key is its distance from home. Press New keys.
Seeded random keys; home slot k mod 13. Distance 0 means the key sits at home.
Cuckoo hashing (Pagh and Rodler, 2001) gives each key two possible cells, T1[h1(k)] and T2[h2(k)]. A lookup checks two cells, always. An insert evicts the resident, which moves to its other cell, and so on. With two tables it works up to about half full.
A Bloom filter (Bloom, 1970) is not a table, but it is built from hashes. Each key sets k bits in a bit array. A query answers "maybe present" if all k bits are set, else "absent". With 10 bits per key and k = 7, it says "maybe" for 0.82% of absent keys and never misses a present one.
Failure. A Java map holds two keys that are equal, and get returns nothing. The class overrides equals but not hashCode, so equal keys land in different slots. Measure: assert that equal objects have equal hashes. Fix: override both, and never change a key after insert.
Chapter 10
Keep the numbers, the checks and the code in one place
A hash table computes where a key lives. Collisions start early, so it needs a rule: chains, which cost 1 + α, or probes, which cost about 1/(1 − α). A random function stops attacks, doubling keeps α bounded at O(1) amortized cost, and a fixed set can have no collisions at all.
| Term | Meaning | Number to remember |
|---|---|---|
| Collision | Two keys, one slot | Even odds after about 1.18√m keys; 38 keys for 1,000 slots |
| Division method | k mod m | Prime m; multiples of 8 into 32 slots use only 4 |
| Multiplication method | ⌊m (kA mod 1)⌋ | A = 0.618; h(123,456) = 4 for m = 1,024 |
| Universal family | ((ak + b) mod p) mod m | Any pair collides in at most 1/m of the functions |
| Load factor α | n/m | Chaining miss 1 + α; grow near 0.75 |
| Uniform probing | Double hashing, near ideal | Miss 1/(1 − α): 10 probes at 0.9 |
| Linear probing | Next slot, then the next | Miss ½(1 + 1/(1 − α)2): 50.5 at 0.9 |
| Rehash by doubling | New array, every key moves | Total work under 3n: 286 for 100 inserts |
| Perfect hashing | Two levels, nj2 cells | E[collisions] < 1/2 per slot; space under 2n on average |
pythonclass HashMap: # chaining, doubling at alpha 0.75 def __init__(self, m=8): self.m, self.n = m, 0 self.slots = [[] for _ in range(m)] def _chain(self, key): return self.slots[hash(key) % self.m] def put(self, key, value): chain = self._chain(key) for i, (k, _) in enumerate(chain): if k == key: chain[i] = (key, value); return # update in place chain.append((key, value)); self.n += 1 if self.n / self.m > 0.75: self._grow() def get(self, key): for k, v in self._chain(key): if k == key: return v raise KeyError(key) def _grow(self): # rehash: every key moves old = [kv for chain in self.slots for kv in chain] self.m *= 2 self.slots = [[] for _ in range(self.m)] for k, v in old: self._chain(k).append((k, v))
| Pattern | The map holds | Example |
|---|---|---|
| Complement lookup | Each value seen, with its index | Two Sum: is target − x already in the map? |
| Frequency count | Item to count | First character that appears once |
| Canonical grouping | Normal form to group | Anagrams keyed by their sorted letters |
| Prefix sum | Running sum to count | Subarrays that sum to k |
| LRU cache | Key to a node of a doubly linked list | Get and put in O(1); evict from the list tail |
A hash table has no order. For the smallest key, the next key, or all keys in a range, use a balanced search tree: O(log n) for each, in order.
Now press Present or Teach and explain three things from memory. Say why 38 keys in 1,000 slots likely collide. Derive 1/(1 − α) from the chance of a full slot. Say why doubling makes rehashing cheap on average. Then go back to the hero, set it to 0.90, and say why the linear bar towers over the others.
This lesson re-teaches Chapter 11, "Hash Tables", of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, published by MIT Press. The probe bounds and perfect hashing follow the book. The toys, counts and devices are our own; we checked every count on this page by running the code.