Hash Tables

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.

Search for a missing key

0.50

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

Calculate, Don't Search

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.

Throw keys until two collide

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.

38

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.

Say it aloud

P is about one minus e to the minus k times k minus one over two, divided by m.

P
P the chance that at least two of the k keys share a slot.
≈
is about a close estimate, good when k is much smaller than m.
e−x
e to the minus x the chance that x expected collisions all fail to happen; e is 2.718.
k(k−1)/2
k times k minus one, over two the number of pairs among k keys.
m
m the number of slots in the table.
In plain words

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.

With numbers

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.

  1. Direct-address tables: one slot per possible key, and the cost in space.
  2. Hash functions: the division and multiplication methods.
  3. Universal hashing: a random function an attacker cannot aim at.
  4. Chaining: a list per slot, and the load factor. The hero's Chaining button.
  5. Open addressing: probe sequences and tombstones. The other two buttons.
  6. How full is too full: why the hero's linear bar explodes.
  7. Growing the table: rehash, and why doubling is cheap.
  8. Perfect hashing: no collisions at all, for a fixed set.
  9. Hash tables in practice: Python, Java, Robin Hood, cuckoo and Bloom.
  10. Field guide: numbers, code, patterns and the credit.
A table has 365 slots and keys land at random. About how many keys give a better than even chance of a collision?

Chapter 1

Direct-Address Tables

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.

Count the empty slots

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.

KeysUniverse UDirect table at 8 bytes a slotEmpty with 1,000 keys
Lowercase letters26208 bytesnone, if all 26 appear
Port numbers65,536524 KB98.5%
9-digit IDs1,000,000,0008 GB99.9999%
IPv6 addresses3.4 × 1038impossibleall 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.

You need to record which of the 26 lowercase letters appear in a string. What is the best structure?

Chapter 2

Hash Functions

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.

Spread 100 keys over the slots

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.

Say it aloud

h of k equals the floor of m times, k A mod one.

h(k)
h of k the slot for key k, from 0 to m − 1.
⌊ ⌋
the floor of round down to a whole number.
m
m the number of slots. A power of 2 is fine here.
k
k the key, as a whole number.
A
A a constant between 0 and 1. Knuth suggests (√5 − 1)/2 = 0.6180339887.
mod 1
mod one keep only the fractional part.
In plain words

Multiply the key k by A. Keep only the fractional part. Multiply that by m and round down. The result is the slot.

With numbers

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.

Why does the division method want m prime, and not 1,024?

Chapter 3

Universal Hashing

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.

Say it aloud

h sub a b of k equals a times k plus b, mod p, then mod m.

ha,b(k)
h sub a b of k the slot of key k under the function chosen by a and b.
a
a a random multiplier from 1 to p − 1.
k
k the key, a whole number below p.
b
b a random shift from 0 to p − 1.
mod p
mod p the remainder after dividing by the prime p. This step scrambles the key.
mod m
mod m the remainder after dividing by m. This step picks the slot.
In plain words

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.

With numbers

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

Beat the bad key set

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.

An attacker can send any keys to your web server. Which hash should the server's table use?

Chapter 4

Chaining and the Load Factor

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.

Grow the chains

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.

Say it aloud

C miss equals one plus alpha.

Cmiss
C miss the average cost of a search for a key that is not in the table.
1
one the step that computes h(k) and reads the slot.
α
alpha the load factor n/m: the keys in the average chain, each checked once.
In plain words

Compute the slot. Check every key in its chain, because the missing key could be at the end. The average chain holds α keys.

With numbers

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.

A chained table has m = 10 slots and n = 30 keys. What does an average miss cost?

Chapter 5

Open Addressing

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.

SequenceProbe i goes toWeakness
Linear probing(h′(k) + i) mod mPrimary 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 mKeys with the same home slot follow the same path.
Double hashing(h1(k) + i · h2(k)) mod mClose 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.

Say it aloud

h of k and i equals h one of k plus i times h two of k, mod m.

h(k, i)
h of k and i the slot that probe number i tries for key k.
h1(k)
h one of k the home slot. Here k mod 11.
i
i the probe number: 0, 1, 2, and so on.
h2(k)
h two of k the step size. Here 1 + (k mod 10), never 0. With m prime, the steps reach every slot.
mod m
mod m wrap around the end of the array.
In plain words

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.

With numbers

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.

Probe, delete, search

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.

Keys A, B and C all have home slot 5 and sit in slots 5, 6 and 7 under linear probing. You delete B by emptying slot 6. What does a search for C do?

Chapter 6

How Full Is Too Full

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 + …

Say it aloud

The expected number of probes is at most one over one minus alpha.

E[probes]
the expected number of probes the average count of slots a miss tries, over many random keys.
≤
is at most an upper bound under uniform hashing.
1
one the first probe, which always happens.
α
alpha the fraction of full slots, n/m, below 1.
In plain words

Each probe finds a full slot with chance α, so you need another. Add 1 + α + α2 and so on. That sum is 1 over 1 − α.

With numbers

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.

Say it aloud

E lin is about one half of, one plus one over one minus alpha, squared.

Elin
E lin the average probes of a miss under linear probing.
≈
is about exact as the table grows large.
½
one half of average the 1 and the cluster term.
(1 − α)2
one minus alpha, squared the square is the clustering: runs grow faster than the load.
In plain words

Take 1 − α and square it. Divide 1 by that. Add 1 and halve. Compare with double hashing, where 1 − α is not squared.

With numbers

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.

Fill the table and count probes

Lines are the formulas. Drag the load, switch between misses and hits, and press Run to measure a real table of 1,009 slots.

0.75

Dots come from one seeded run with random keys. Chaining counts the hash step plus keys checked; open addressing counts probes.

αChaining missDouble hashing missLinear missDouble hashing hit
0.501.522.51.39
0.751.7548.51.85
0.901.91050.52.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.

A double-hashing table runs at α = 0.8. You double m, so α drops to 0.4. What happens to the cost of a miss?

Chapter 7

Growing the Table

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.

moves = 6 + 12 + 24 + 48 + 96 = 186, which is under 2 × 100
total = 100 inserts + 186 moves = 286, or 2.86 steps per insert

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.

Pay for the rehashes

The step line is the total work so far; each jump is a rehash. The dashed line is 3n. Switch the growth rule.

1,000

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.

Why is the amortized cost of an insert O(1), though one insert can cost n moves?

Chapter 8

Perfect Hashing

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.

Say it aloud

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.

E[X]
the expected X the average number of colliding pairs in slot j's level-2 table, over the random draw.
nj(nj − 1)/2
n j times n j minus one, over two the number of pairs among the nj keys of slot j.
1/nj2
one over n j squared the most a pair can collide under a universal function on nj2 cells.
< 1/2
less than one half the product simplifies to (nj − 1)/(2nj), always under a half.
In plain words

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.

With numbers

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.

Build a perfect table

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.

Why does each level-2 table get nj2 cells, not nj?

Chapter 9

Hash Tables in Practice

See which textbook ideas the real tables use, and the tricks they add

TableCollisionsGrows atIts trick
Python dictOpen addressing; the next slot is 5j + 1 + perturb, where perturb starts as the full hash and shifts right 5 bits each probe2/3 fullSince 3.6, a dense entry array plus a small index array; it keeps insertion order
Java HashMapChaining0.75A chain longer than 8 becomes a red-black tree, once the table has 64 slots
C++ unordered_mapChaining1.0 by defaultBuckets you can inspect
Swiss Table (Abseil), Rust HashMapOpen addressing7/8 fullOne 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.

Take from the rich

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.

A Bloom filter says "absent" for a key. What do you know?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
CollisionTwo keys, one slotEven odds after about 1.18√m keys; 38 keys for 1,000 slots
Division methodk mod mPrime 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 mAny pair collides in at most 1/m of the functions
Load factor αn/mChaining miss 1 + α; grow near 0.75
Uniform probingDouble hashing, near idealMiss 1/(1 − α): 10 probes at 0.9
Linear probingNext slot, then the nextMiss ½(1 + 1/(1 − α)2): 50.5 at 0.9
Rehash by doublingNew array, every key movesTotal work under 3n: 286 for 100 inserts
Perfect hashingTwo levels, nj2 cellsE[collisions] < 1/2 per slot; space under 2n on average

Checklist

The core, as code

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))

Patterns that reduce to a lookup

PatternThe map holdsExample
Complement lookupEach value seen, with its indexTwo Sum: is target − x already in the map?
Frequency countItem to countFirst character that appears once
Canonical groupingNormal form to groupAnagrams keyed by their sorted letters
Prefix sumRunning sum to countSubarrays that sum to k
LRU cacheKey to a node of a doubly linked listGet 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.

Keep going

The takeaway. Cost depends on how full the table is, not on how big it is. Keep α bounded, pick the function at random, and plan for collisions from the first key.
You need O(1) average lookup and also the keys in sorted order. What do you use?

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.

Credit and source

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.

CLRS Chapter 11: Hash Tables
Next: Binary Search Trees · Back to Gleams