Hash Tables
Hash functions, collisions, chaining and open addressing.
Python's dict, Java's HashMap and C++'s unordered_map all promise constant time on average, yet no two are built alike: one probes for free slots, one keeps chains that turn into trees, one keeps plain chains. This lesson derives what each design costs at a given load factor, proves the bound for chaining, explains tombstones and resizing, and shows how to spot a hash-table problem in a statement.
What you’ll learn
- Design hash functions for integers (division, multiplicative, multiply-shift) and strings (polynomial), and choose the table size .
- Prove that a chained table compares keys per unsuccessful search and per successful search in expectation, under simple uniform hashing.
- Compare linear probing, quadratic probing and double hashing; prove the bound for uniform hashing and use Knuth's formulas for linear probing.
- Implement deletion with tombstones and resizing with amortized insertions.
- Recognize hash-table problems (counting, deduplication, two sum, grouping, memoization) and the look-alikes that need ordered structures instead.
Hash functions: from keys to slots
A hash function maps keys from a huge universe to the slots of a hash table. It must be deterministic (the same key always gets the same slot), fast, and it should spread the keys evenly. The analyses below assume simple uniform hashing: every key lands in a uniformly random slot, independently of the other keys.
No fixed function satisfies that assumption for every possible input; the Optimized lesson Universal Hashing & Sketches shows how randomizing the function recovers it as a guarantee. On ordinary data, the standard functions behave close enough to it:
| Method | Choice of | |
|---|---|---|
| Division | A prime not close to a power of 2. With it keeps only the lowest bits of . | |
| Multiplicative (Knuth) | , with | Any , powers of 2 included. |
| Multiply-shift | , with | : one multiplication and one shift on a -bit word. |
| Polynomial (strings) | for characters | A prime ; Java's String.hashCode uses and arithmetic modulo . |
0x9E3779B97F4A7C15, a constant you will meet again in the Optimal lesson Hash Flooding & Anti-Hash Tests.import math
A = (math.sqrt(5) - 1) / 2 # Knuth's suggestion, about 0.618
def h_division(k, m): # m prime, not close to a power of 2
return k % m
def h_multiplicative(k, m): # any m, powers of 2 included
return math.floor(m * ((k * A) % 1))
def h_multiply_shift(k, p, w=64): # the same idea in integer arithmetic, m = 2**p
s = 0x9E3779B97F4A7C15 # floor(A * 2**64)
return ((s * k) % (1 << w)) >> (w - p)
def h_string(s, m, b=31): # polynomial hash, evaluated by Horner's rule
h = 0
for ch in s:
h = (h * b + ord(ch)) % m
return hThe consecutive keys 1000, 1001, 1002 and 1003 go to slots 0, 10, 4 and 14 of a 16-slot table under both h_multiplicative and h_multiply_shift: the golden ratio scatters neighbors. (The floating-point version loses precision for very large keys; the integer one is exact.)
Chaining, analyzed
In chaining, slot holds a list of the keys with . An insertion scans the chain to rule out a duplicate, then appends; a search scans the chain; a deletion unlinks the key, in once it has been found if the lists are doubly linked. In the worst case every key shares one chain and each operation takes . The expected case depends only on the load factor , which for chaining may exceed 1.
Unsuccessful search. The searched key's slot is uniform and independent of the stored keys, and each stored key lands in that slot with probability . By linearity of expectation, the chain it scans has expected length
Successful search. Let be the keys in insertion order. Since keys are appended, a search for compares itself plus every earlier key in its chain. With indicators and for :
Sum the arithmetic series:
Inserting at the head of the chain instead, as CLRS does, makes a search for scan the keys inserted after it; by symmetry the count is the same. If grows with so that , every operation takes expected time:
A chained table has slots and holds keys under simple uniform hashing. In expectation, how many keys does an unsuccessful search compare, and how many does a successful search compare?
- 3 and 3
- 3 and about 2.5
- 1.5 and about 2.5
- 3,000 and 1,500
Show the answer
B. 3 and about 2.5
An unsuccessful search scans a whole chain of expected length . A successful search scans, on average, the key itself plus half of the others in its chain: .
Open addressing: probe sequences
Open addressing stores the keys in the array itself, one per slot, so . Each key has a probe sequence of slots. An insertion takes the first free slot on it; a search follows it until it finds the key or an empty slot. Three classic sequences, for a home slot :
- Linear probing: . Cache-friendly, but runs of occupied slots merge and grow: primary clustering.
- Quadratic probing: . Keys with different home slots spread apart, but keys with the same home slot share a sequence (secondary clustering). With a prime it visits only different slots, which is enough to always find a free one while .
- Double hashing: , with never 0 and coprime to , for example with a prime . The step depends on the key, so a prime gives different sequences.
Unsuccessful. Let be the number of probes. The first probes all hit occupied slots only if each successive probe, at a slot not yet seen, finds one of the remaining keys:
A nonnegative integer variable has , so a geometric series bounds it:
Successful. Without deletions, a search for the key inserted -st retraces that key's insertion, which was an unsuccessful search when the table held keys. Averaging over the keys:
Linear probing violates uniform hashing badly: a run of occupied slots attracts every key that hashes into it. Knuth's analysis (1963) gives its exact expected costs with a random hash function, about probes for a successful search and for an unsuccessful one. The square is the price of clustering:
| Uniform hashing: absent / present | Linear probing: absent / present | Chaining: keys compared, absent / present | |
|---|---|---|---|
| 0.5 | 2 / 1.39 | 2.5 / 1.5 | 0.5 / 1.25 |
| 0.75 | 4 / 1.85 | 8.5 / 2.5 | 0.75 / 1.375 |
| 0.9 | 10 / 2.56 | 50.5 / 5.5 | 0.9 / 1.45 |
Deletion, resizing and the table size
Deleting from a chained table just unlinks the key. In open addressing you may not simply empty the slot: a search for any key whose probe sequence passed through that slot would now stop there and report a false "absent". Instead the slot gets a tombstone:
- searches step over tombstones as if they were occupied;
- an insertion first confirms that the key is absent (which means probing to an empty slot), then stores it in the first tombstone it passed, if any;
- tombstones lengthen searches exactly as keys do, so they count toward the load that triggers a rebuild, and a rebuild drops them all.
For linear probing there is an alternative without tombstones, Knuth's Algorithm R: after emptying a slot, walk forward through the rest of the cluster and move back every key whose probe path crosses the hole.
Resizing. When an insertion would push the load factor past a threshold (with chaining often 1, with open addressing 0.5 to 0.875), the table allocates about twice as many slots and rehashes: it reinserts every live key, because depends on and every key's slot changes. One resize costs ; the doubling makes it cheap on average.
Start with slots and double whenever an insertion would exceed . The resizes happen at sizes that double each time, and the last one before the -th insertion moves at most keys. So the total number of keys ever moved is
Each insertion also costs expected probes for itself (the load factor stays below ), so insertions cost expected time: expected, amortized, per insertion.
Growing by a fixed number of slots instead resizes after every insertions, and the -th resize moves about keys:
Shrinking follows the dynamic-array rule: halve when falls below , not , so that after any resize operations must happen before the next one. Halving at would let alternating insertions and deletions at the boundary resize every time.
Prime or power of two? A prime makes the division method robust to patterns in the keys and makes every step of double hashing coprime to . A power of two replaces the division by a bit mask, which is much faster, but then the hash function itself must mix the high bits of the key into the low ones: Java's HashMap folds the hash with , multiply-shift takes the top bits of a product, and CPython's probe sequence shifts in more of the hash at every step.
EMPTY, TOMB = object(), object() # TOMB marks a deleted slot (a tombstone)
class LinearProbingSet:
def __init__(self, m=8):
self.slots, self.used = [EMPTY] * m, 0 # used = live keys + tombstones
def _find(self, key): # -> (slot holding key or None, slot to insert into)
m = len(self.slots)
i, free = hash(key) % m, None
while self.slots[i] is not EMPTY: # an EMPTY slot exists, since used <= 3m/4
if self.slots[i] is TOMB:
free = i if free is None else free
elif self.slots[i] == key:
return i, None
i = (i + 1) % m
return None, (i if free is None else free)
def __contains__(self, key):
return self._find(key)[0] is not None
def add(self, key):
if self.used + 1 > 0.75 * len(self.slots): # rebuild without tombstones
live = [k for k in self.slots if k is not EMPTY and k is not TOMB]
m = len(self.slots) * (2 if 2 * len(live) >= len(self.slots) else 1)
self.slots, self.used = [EMPTY] * m, 0
for k in live:
self.add(k)
found, j = self._find(key)
if found is None:
self.used += self.slots[j] is EMPTY # reusing a tombstone uses no new slot
self.slots[j] = key
def remove(self, key):
found, _ = self._find(key)
if found is not None:
self.slots[found] = TOMB # not EMPTY: that would cut other keys' probe pathsA set with linear probing, tombstones and resizing. The rebuild doubles the table only when live keys fill at least half of it; when the used slots are mostly tombstones it rebuilds at the same size, so a long run of insertions and deletions cannot inflate the table. Tested against Python's own set on random operation sequences.
What your language actually does
| Library | Collisions | Size and growth | Worth knowing |
|---|---|---|---|
CPython dict | Open addressing. From slot the next probe is modulo the size; perturb starts as the full hash and is shifted right by 5 bits each step, so every bit of the hash eventually matters. | A power of 2, at least 8 slots; grows when 2/3 full. Deleted slots are marked as dummies, CPython's tombstones. | The entries live in a dense array in insertion order (since 3.6; guaranteed by the language since 3.7), indexed by the hash table. |
C++ std::unordered_map | Separate chaining: bucket iterators, and references that stay valid across rehashing, effectively require it. | max_load_factor() defaults to 1.0. GCC's libstdc++ takes prime bucket counts from a fixed table. | std::hash of an integer is the integer itself, in both libstdc++ and LLVM's libc++. |
Java HashMap | Chaining; the hash is spread as before masking. | A power of 2, 16 by default; grows at load factor 0.75. | Adding a key to a bin that already holds 8 entries turns the bin into a red-black tree, once the table has at least 64 bins (a smaller table grows instead). Colliding keys then cost if their hashes differ or they are Comparable. |
Abseil flat_hash_map, Rust's HashMap, Go's maps (since Go 1.24) | "Swiss tables": open addressing over groups of slots, one control byte per slot holding 7 bits of the hash; a whole group is compared at once with SIMD instructions. | Abseil grows at load 7/8. | Rust's default hasher is SipHash-1-3 with a random key per map. |
Two more facts about Python matter in practice. Strings and bytes are hashed with a keyed function (SipHash-1-3 since Python 3.11) whose secret key is drawn at random when the process starts, so hash("abc") changes from run to run unless PYTHONHASHSEED is set. Integers are not randomized: on 64-bit builds a non-negative int hashes to its value modulo the prime , so small integers hash to themselves.
#include <unordered_map>
#include <vector>
long long count_equal_pairs(const std::vector<long long>& a) {
std::unordered_map<long long, long long> cnt;
cnt.reserve(a.size()); // allocate the buckets once: no rehash in the loop
long long pairs = 0;
for (long long x : a) pairs += cnt[x]++; // operator[] inserts x with count 0 if it is new
return pairs;
}
// To test membership without inserting, use cnt.count(x) or cnt.find(x) != cnt.end(), never cnt[x].The contest idiom for counting: on it returns 4 (three pairs of 3s and one pair of 1s). reserve avoids the intermediate rehashes, and the comment marks the most common unordered_map bug.
Recognizing it
A hash table is the answer whenever the question is about exact matches: "have I seen this?", "how many times?", "where was it?", "which group does it belong to?". Statement signals: count, frequency, distinct, duplicate, first repeated, pair or complement, group by, anagram, cache, visited. Constraints such as to with values up to rule out both an comparison of all pairs and a direct-address array indexed by value; expected time with a hash map fits easily.
| Problem | Key idea | Cost |
|---|---|---|
| Two sum on unsorted data: two positions whose values add up to | Scan once with a map from value to position; before storing , look up | expected |
| Group anagrams | Canonical key: the word's letters in sorted order, or its tuple of 26 letter counts | , or with counts |
| Longest run of consecutive integers in an unsorted array | Hash set of the values; walk upward only from an whose is absent, so each value is visited times | expected |
| Number of subarrays with sum | Prefix sums ; count how many earlier prefixes equal with a map of counts | expected |
| LRU cache with get and put | A map from key to a node of a doubly linked list kept in order of recent use | expected per operation |
from collections import defaultdict
def two_sum(a, target): # indices i < j with a[i] + a[j] == target
seen = {} # value -> index where it was first seen
for j, x in enumerate(a):
if target - x in seen:
return seen[target - x], j
seen.setdefault(x, j)
return None
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups[''.join(sorted(w))].append(w) # canonical key: the letters in sorted order
return list(groups.values())
def longest_consecutive(a): # longest run x, x+1, x+2, ... present in a
s, best = set(a), 0
for x in s:
if x - 1 not in s: # x starts a run: walk it once
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return besttwo_sum([8, 3, 5, 9, 2], 11) returns (0, 1); longest_consecutive([100, 4, 200, 1, 3, 2]) returns 4. Looking up before storing is what stops a value from pairing with itself.
Common bugs:
- Mutable keys. Python refuses to hash a
list(use atuple); in Java, mutating an object after using it as a key strands it in the wrong bin. OverridingequalswithouthashCodebreaks lookups. cnt[x]to test membership in C++, which inserts . Usecountorfind.- Unhashable composite keys in C++:
std::unordered_map<std::pair<int, int>, int>has no default hash. Encode the pair as one 64-bit integer, or write a hash. - Floating-point keys:
0.1 + 0.2 != 0.3, andNaNis not equal to itself, so lookups miss. Round or scale to integers first. - Trusting the average under attack: a hash function that is fixed and public turns expected into on hacking tests. See the Optimal lesson Hash Flooding & Anti-Hash Tests.
A program must process operations on a set of integers up to : insert , delete , and "report the smallest stored value greater than ". Which structure fits?
- A hash set, scanning all stored values for the third query
- A balanced binary search tree, such as C++'s
std::setwithupper_bound - An array indexed by value
- A hash map from each value to its successor, updated on every insertion and deletion
Show the answer
B. A balanced binary search tree, such as C++'s std::set with upper_bound
The third query is about order, which hashing destroys. A balanced search tree keeps the keys sorted and answers insert, delete and successor in each: about steps in total.
Key takeaways
- Good hash functions spread keys like random numbers: the division method with a prime , the multiplicative method or multiply-shift for , and polynomial hashing for strings.
- Under simple uniform hashing, chaining compares keys per unsuccessful search and per successful one in expectation, so when ; the worst case is .
- Open addressing under uniform hashing needs at most expected probes per unsuccessful search; linear probing pays about because of primary clustering, so open-addressing tables keep well below 1.
- Deletion in open addressing needs tombstones (or Knuth's backward shift for linear probing), and doubling on resize keeps insertions amortized, where growing by a constant costs in total.
- Reach for a hash table on exact-match questions (counting, deduplication, two sum, grouping, memoization) and for a sorted structure on order questions (successor, ranges); every library promises only expected .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Under uniform hashing, an open-addressing table is 80% full. What does the theorem guarantee about the expected number of probes in an unsuccessful search?
- At most 1.25
- At most about 2.01
- At most 5
- At most 13
Show the answer
C. At most 5
: each probe finds an occupied slot with probability at most , so the number of probes is dominated by a geometric variable with mean 5.
Keys are memory addresses, all multiples of 16, stored in a table of slots with . What goes wrong?
- Nothing: the remainder spreads any keys evenly
- Only 64 of the 1,024 slots can ever be used, so chains are about 16 times longer than they should be
- Large addresses overflow the remainder
- Every key lands in slot 0
Show the answer
B. Only 64 of the 1,024 slots can ever be used, so chains are about 16 times longer than they should be
keeps the lowest 10 bits of , and the lowest 4 are always 0, so only the slots that are multiples of 16 can be hit. A prime , or a multiplicative hash that mixes high bits into the index, uses all 1,024.
Which of these tasks is the poorest fit for a hash table?
- Count how often each word occurs in a book
- Remove duplicate records from a list
- List all stored keys between and in increasing order
- Cache the results of an expensive function of two integers
Show the answer
C. List all stored keys between and in increasing order
A hash function scatters keys on purpose, so keys near each other in value land far apart, and a range query must examine every key. A balanced search tree or a sorted array answers it in for reported keys.
A linear-probing table has 1,000 slots, 400 live keys and 450 tombstones, so its load factor counting live keys only is 0.4. Why should it be rebuilt?
- It should not: at linear probing is fast
- Tombstones make some successful searches return the wrong key
- Searches stop only at empty slots, so they behave as if 850 slots were full: Knuth's estimate for an unsuccessful search rises from about 1.9 probes to about 23
- New keys can no longer be inserted into tombstones
Show the answer
C. Searches stop only at empty slots, so they behave as if 850 slots were full: Knuth's estimate for an unsuccessful search rises from about 1.9 probes to about 23
For probing, a tombstone is as good as a key: probes at becomes when 85% of the slots are in use. A rebuild reinserts the 400 live keys and drops all 450 tombstones.
A table grows by a fixed 1,000 slots each time it becomes full, instead of doubling. About how many keys do all the rehashes move during insertions?
- Fewer than
- About
- About
- About
Show the answer
C. About
Resizes happen at 1,000, 2,000, 3,000, … keys, and the -th moves keys: . That is for growth by slots, against fewer than for doubling.
Go deeper
- Open Addressing in Depth · Linear probing’s analysis, Robin Hood hashing, and the 2025 disproof of Yao’s conjecture.
- Cuckoo Hashing & Perfect Hashing · Worst-case O(1) lookups: two choices, FKS and minimal perfect hashing.
- Hash Flooding & Anti-Hash Tests · Inputs that make hash tables quadratic, and the defenses against them.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 11.
- D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.4.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 3.4.