Section 14.7

Hash table

Definition

A hash table is a data structure that stores entries, each a key with associated data, in an array §14.5 of positions called buckets. A hash function turns each key into a number, the hash code, that selects the key’s bucket. Different keys can get the same bucket, a collision, so the table resolves collisions and compares stored keys in full before reporting a match. If keys spread evenly and the entries per bucket stay bounded, an operation takes on average a number of steps independent of the number of entries.

The idea

A program must find one of 1,000 user records, by user name, on every request. Scanning an unsorted array compares up to 1,000 names. A sorted array searched by binary search, which halves the candidates at each comparison, needs about 10 comparisons, since 210=10242^{10} = 1024, but each new user means moving records to keep the order. A hash table computes a bucket number from the name and looks only in that bucket.

A mail room with 100 pigeonholes, numbered 00 to 99, works the same way. Letters are sorted by the last two digits of the apartment number, so mail for apartment 1234 goes to pigeonhole 34. To collect mail for apartment 1234, the clerk looks only in pigeonhole 34 and then reads the full apartment number on each letter there, because mail for apartment 3334 also lands in pigeonhole 34. The pigeonhole is the bucket, taking the last two digits is the hash function, and reading the full number is the key comparison. The picture stops at the choice of digits. A real hash function mixes every part of the key, because real keys often agree in some part: many file names end in the same four characters .txt, and a function that looked only at the last characters would put them all in one bucket.

How it works

The parts have these names.

Separate chaining gives each bucket a linked list §14.6, called its chain, of all entries whose keys have that bucket index.

  1. To look up key kk, compute i=h(k)modmi = h(k) \bmod m.

  2. Walk the chain of bucket ii, comparing each stored key with kk.

  3. Report the entry whose key equals kk, or report that kk is absent at the end of the chain.

Insertion looks the key up first, replaces the associated data if the key is present, and otherwise adds a new entry to the chain. Removal unlinks the entry from its chain.

Open addressing stores at most one entry in each bucket. A key whose bucket is taken tries other buckets in a fixed order called its probe sequence.

  1. Compute the start bucket i=h(k)modmi = h(k) \bmod m.

  2. Examine buckets in probe order. In linear probing the order is i,i+1,i+2,…i, i + 1, i + 2, \dots, wrapping from bucket m−1m - 1 back to bucket 0.

  3. Stop with success at a bucket that holds kk. Stop with absence at a bucket that has never held an entry, or after mm buckets, when every bucket has been examined.

Other probe orders exist: quadratic probing steps by growing distances, and double hashing takes the step size from a second hash function. Removal cannot simply empty a bucket, because another key may have passed through that bucket on its way to its own, and an empty bucket would end that key’s lookups early. The bucket gets a tombstone instead, a marker that means “deleted, keep searching”. Lookups pass over tombstones, and insertions may reuse them.

Growth. When α\alpha passes a threshold, the table allocates a larger array, often twice as large, and reinserts every entry, because every bucket index depends on mm. Java’s HashMap, for example, doubles its array when α\alpha exceeds 0.75 by default. An insertion that triggers growth costs time proportional to nn, but doubling makes such insertions rare. Amortized analysis §14.4, which spreads the cost of rare expensive steps over the cheap steps around them, shows that the average cost per insertion does not grow with nn.

Reduction to a bucket. The bucket index keeps only part of the information in the hash code. With m=8m = 8 and h(k)=kh(k) = k, the keys 0, 8, 16 and 24 all leave remainder 0 and share bucket 0. With m=7m = 7 they leave remainders 0, 1, 2 and 3. A table whose mm is a power of two keeps only the low bits of the hash code, so it needs a hash function that mixes every bit of the key into those low bits.

Worked example

Take m=8m = 8 buckets and the toy hash function h(k)=kh(k) = k for number keys, so the bucket of key kk is kmod8k \bmod 8. Insert the keys 3, 11, 19 and 27. Each leaves remainder 3: 3=0×8+33 = 0 \times 8 + 3, 11=1×8+311 = 1 \times 8 + 3, 19=2×8+319 = 2 \times 8 + 3 and 27=3×8+327 = 3 \times 8 + 3. The load factor is α=4/8=0.5\alpha = 4 / 8 = 0.5.

Separate chaining puts all four keys in the chain of bucket 3. A lookup of key 35, where 35=4×8+335 = 4 \times 8 + 3, compares 35 with 3, 11, 19 and 27, finds no match and reports absence after 4 comparisons. Had the keys been 3, 4, 5 and 6, each would sit alone in its own bucket, and the same lookup would make 1 comparison. Both tables have α=0.5\alpha = 0.5. The load factor is an average and does not reveal the long chain.

Linear probing places 3 in bucket 3. Key 11 starts at bucket 3, finds it taken, and moves to bucket 4. Key 19 tries buckets 3 and 4 and lands in bucket 5, and key 27 tries 3, 4 and 5 and lands in bucket 6. A lookup of 35 examines buckets 3, 4, 5 and 6, which hold other keys, and stops at bucket 7, which has never been used: 5 buckets examined to report absence. The four keys now form a run, a block of consecutive taken buckets, and every key whose start bucket lies anywhere from 3 to 6 must walk to the end of that run.

Removal. Remove 11 from bucket 4. If bucket 4 were simply emptied, a lookup of 19 would examine bucket 3, which holds 3, then bucket 4, which is empty, and stop, reporting 19 absent although 19 sits in bucket 5. With a tombstone in bucket 4, the lookup passes over bucket 4 and finds 19 in bucket 5, after examining 3 buckets.

Stated precisely

Let nn be the number of entries, m≥1m \ge 1 the number of buckets and α=n/m\alpha = n / m the load factor. Write O(f)O(f) for a quantity that is at most a constant times ff. The simple uniform hashing assumption states that each key lands in each of the mm buckets with probability 1/m1/m, independently of every other key. Under that assumption, with separate chaining, the bucket that a missing key maps to holds on average n×(1/m)=αn \times (1/m) = \alpha entries, because each of the nn stored keys lies in that bucket with probability 1/m1/m. A lookup of a missing key therefore costs one hash computation plus α\alpha key comparisons on average, which is O(1+α)O(1 + \alpha). A lookup of a present key also costs O(1+α)O(1 + \alpha) on average.

For open addressing, the uniform hashing assumption states that the probe sequence of each key is equally likely to be any of the m!m! orders of the mm buckets, where m!m! is the product 1×2×…×m1 \times 2 \times \dots \times m. Under it, with α<1\alpha < 1, the expected number of buckets examined is at most 1/(1−α)1 / (1 - \alpha) for a lookup of a missing key and at most (1/α)ln(1/(1−α))(1 / \alpha) \ln (1 / (1 - \alpha)) for a lookup of a present key, where ln\ln is the natural logarithm. Linear probing does worse because runs merge and grow. Knuth’s classical analysis gives about 12(1+1/(1−α)2)\frac{1}{2}(1 + 1 / (1 - \alpha)^2) buckets for a missing key and 12(1+1/(1−α))\frac{1}{2}(1 + 1 / (1 - \alpha)) for a present key: 2.5 and 1.5 at α=0.5\alpha = 0.5, and 50.5 and 5.5 at α=0.9\alpha = 0.9.

These are averages, and they rest on three assumptions besides the hashing assumption: the keys do not depend on the hash function, computing h(k)h(k) and comparing two keys each take a fixed number of steps, and growth keeps α\alpha below a fixed bound. Long keys break the second assumption, since hashing or comparing a long text costs time proportional to its length. In the worst case all nn keys share one bucket, and a lookup compares all nn of them.

Limits and common mistakes

Expected constant time is not a worst-case bound. An attacker who knows the hash function can choose keys that all land in one bucket, so that inserting nn of them costs 0+1+…+(n−1)=n(n−1)/20 + 1 + \dots + (n - 1) = n(n - 1)/2 key comparisons in total. This is an algorithmic complexity attack §15.35, a form of denial of service §1.28 that Crosby and Wallach demonstrated against real programs in 2003 [241]. The defenses are a hash function that mixes in a secret random seed, such as SipHash, by Jean-Philippe Aumasson and Daniel J. Bernstein, which Python §12.23 and Rust use for strings (cryptographers call such a seed a key; this entry says seed to keep it apart from table keys); a limit on chain length or probe count; or a balanced search tree §14.10 inside each overfull bucket, as in Java’s HashMap since Java 8.

A matching bucket is not a matching key. Two keys in one bucket, or two keys with the same full hash code, are still different keys. A table that reports a match without comparing the keys returns another key’s data.

A key must not change while it is stored. A changed key has a new hash code, but its entry stays in the bucket of the old one, where lookups of the new key never look.

Equal keys must have equal hash codes. If a program treats two keys as equal, for example two spellings of a name that differ only in upper and lower case, the hash function must ignore the same differences.

Growth is a pause. The insertion that triggers growth moves every entry, which a real-time system §6.34 may not afford. Such systems use a table of fixed size or move entries a few at a time, a technique called deamortization §14.40.

A hash table keeps no order. It cannot list keys in sorted order or answer a range question such as “all keys from 100 to 200” without examining every entry; a balanced search tree can.

Open addressing degrades sharply as α\alpha approaches 1, and tombstones slow lookups as entries do; the Load factor entry treats a nearly full table of fixed size. A hash code chosen for spreading keys is no security mechanism; the Hash collision versus cryptographic collision §14.8 entry explains why.

Questions answered

Which collision patterns produce long chains or probing sequences?

Long chains and long probe sequences come from keys that pile up on a few buckets and from tables that are nearly full. A hash table turns each key into a number, the hash code, and reduces it to a bucket index; separate chaining keeps a list, the chain, per bucket, and open addressing stores one entry per bucket and sends a key whose bucket is taken through other buckets in a fixed order, its probe sequence. The patterns are these.

The defenses are a hash function that mixes every bit of the key, growth before the table fills, a cap on chain length or probes, and, for keys from untrusted sources, a hash function with a secret random seed, such as SipHash.

Related entries: Worst-case versus average-case complexity (§14.3), Hash collision versus cryptographic collision (§14.8), Load factor (§14.9), Amortized analysis (§14.4), Deamortization: spreading array migration while preserving lookup meaning (§14.40), Algorithmic complexity attack (§15.35). Further reading: [241].