Module contents
Lesson 7 of 33Core 115 min

Hashing: tables, universality and adversaries

Hash tables are programming's most widely used data structure, and their analysis requires randomness. Study chaining and open addressing, including linear probing and Robin Hood hashing; Carter-Wegman universal hashing and k-wise independence; cuckoo hashing; and FKS perfect hashing. Finish with hash-flooding attacks, SipHash, and the design of CPython dictionaries.

After this lesson you can

  • Analyze the expected cost of searches with chaining and with linear probing as a function of the load factor.
  • Prove that the family ((ax + b) mod p) mod m is universal and implement it.
  • Implement cuckoo hashing and explain when and why the table should be reconstructed.
  • Build a two-level perfect hash table and demonstrate that its expected space is O(n).
  • Reproduce hash flooding against an unkeyed hash function and explain CPython's defense.

Before you start

Motivation: a constant-time dictionary, unless someone works against you

A dictionary stores key-value pairs and answers three questions: is this key present, what value does it have, and can you insert or remove it? It is the most widely used data structure in programming: Python’s dict and set, JavaScript objects, the indices used by a database hash JOIN, deduplication of a training corpus, memoization of a recursive computation, a results cache, and a tokenizer’s vocabulary. In all these settings, the expectation is the same: constant time per operation.

The idea is simple. If keys were small integers, an array would suffice: key kk lives in cell kk. But the universe UU of possible keys (strings, 64-bit integers, tuples) is astronomical compared with the number nn of keys you actually store. A hash function h:U→{0,…,m−1}h : U \to \{0, \dots, m-1\} compresses each key to an index in a table of mm cells, with mm on the order of nn. The price is unavoidable: by the pigeonhole principle, if ∣U∣>(n−1)m\abs{U} > (n-1)m, for any fixed hh there exist nn keys that all fall into the same cell. A deterministic hash function cannot be good for every set of keys.

There are two ways out. The first assumes that keys behave like random data (this gives the simplest analysis, and is what you unknowingly assume whenever you write d[k] = v). The second is to randomize the function: let the adversary choose the keys first, then draw hh at random from a sufficiently rich family. This is exactly the same change in philosophy as in randomized quicksort: the worst case becomes an event of low probability over the algorithm’s random choices, rather than a particular input. The difference from quicksort is that hash tables run on servers receiving data from strangers, so the first approach leaves a security vulnerability: in December 2011, at the 28C3 conference, Klink and Wälde showed that a single carefully constructed HTTP request could keep a web server processor busy for a long time across several languages and platforms, simply by choosing parameter names that collided in the hash table used to store them (Crosby and Wallach had published the idea in 2003).

This lesson follows the whole story. First come the two ways to resolve collisions, chaining and open addressing, and their costs as the table fills up. Next come universal hashing, which turns the assumption ‘keys are random’ into a provable guarantee, the hierarchy of independence assumptions required by each scheme, and two structures with stronger guarantees than an ordinary table: two-level perfect hashing (FKS) and cuckoo hashing. We finish with adversaries (hash-flooding attacks and SipHash) and the actual design of CPython’s dictionary, which you will use every day.

Chaining and load factor

A hash table with chaining has mm buckets, each storing a list of the keys kk whose h(k)h(k) equals its index. Insertion adds a key to the list after checking that it is absent; lookup traverses the list for h(k)h(k); deletion removes the key from that list. The quantity governing everything is the load factor

α=nm,\alpha = \frac{n}{m},

the mean bucket size. With chaining, α\alpha can exceed 11: the table does not fill up; its chains simply grow longer.

What must we require of hh? The minimum needed for the analysis: two distinct keys should almost never share a bucket.

A function that maps each key uniformly and independently of all others satisfies this property with equality (this is called simple uniform hashing), but much less is required. For now, assume such a family exists; the section on universal hashing shows how to obtain one with just a few random bits.

Proof

Use the familiar analysis with indicator variables. For y∈Sy \in S, let Xy=1[h(y)=h(k)]X_y = \ind[h(y) = h(k)]. The bucket for kk has length ∑y∈S∖{k}Xy\sum_{y \in S \setminus \{k\}} X_y (plus 11 if k∈Sk \in S), and linearity of expectation together with the collision property gives E[Xy]=P[h(y)=h(k)]≤1/m\E[X_y] = \Pr[h(y) = h(k)] \le 1/m. This proves (1). For (3), apply the same argument to the (n2)\binom{n}{2} pair indicators. For (2), looking up a key yy compares it with every colliding key preceding it in the list and with itself. Each colliding pair {x,y}\{x, y\} contributes exactly one comparison: the later key is compared with the earlier one. The total number of comparisons over all keys is therefore nn plus the number of colliding pairs, whose expectation is at most (n2)/m\binom{n}{2}/m. Dividing by nn gives 1+n−12m1 + \frac{n-1}{2m}.

∎

Thus, as long as mm is proportional to nn, each operation costs Θ(1)\Theta(1) in expectation. To keep α\alpha bounded, use what you already know about a dynamic array: when nn exceeds mm, double the table and reinsert everything with a new function. Each rebuild costs O(n)\bigO(n), but occurs only after Ω(n)\Omega(n) insertions. Amortized analysis distributes this cost, giving an expected amortized cost of O(1)\bigO(1) per insertion.

Open addressing: linear probing, Robin Hood and tombstones

Linked lists are slow on a real processor: each node requires an access to noncontiguous memory. Open addressing stores keys inside the table itself, an array of m≥nm \ge n cells, and resolves collisions by looking for another cell. Key kk follows a probe sequence h(k,0),h(k,1),…h(k, 0), h(k, 1), \dots until it finds a free cell when inserting, or the key itself or an empty cell when searching. With linear probing, h(k,i)=(h(k)+i) mod mh(k, i) = (h(k) + i) \bmod m: try the next cell, then the next. The mm probes eventually visit the entire table, and the load must satisfy α<1\alpha < 1.

The figure shows what happens. It contains an actual 64-cell table, colored by each key’s displacement from its home cell, and curves measured on 1024-cell tables alongside the theoretical formulas.

InteractiveLoad factor versus probes
A table of m=64m = 64 with n=51n = 51 keys
32152133510101171235
color = distance to the origin:0 to 5+largest cluster (underlined)unsuccessful lookup
Mean probes versus α\alpha (tables of 1024 cells, log scale)
  • successful, measured
  • unsuccessful, measured
  • successful, theory
  • unsuccessful, theory
Scheme
Load and deletion
0.80
After deleting 40% of the keys
Successful search3.10 (theory 3.00)
Unsuccessful search12.57 (theory 13.00)
Largest cluster (64 cells)35
Live / effective occupancy0.80 / 0.80
Unsuccessful lookup from cell 2536 probes
With α=0.80\alpha = 0.80 the keys form clusters that grow and merge (the longest streak is of 35 cells): a failed search that falls into one traverses the entire cluster.
Increase the load factor α\alpha with linear probing and see how the keys merge into clusters (the largest, underlined in orange) and how the red curve of failed search spikes (compare it with the chaining one). Click any cell to initiate a failed search from it: within a cluster, you have to traverse it to the end. Switch to Robin Hood and compare the color of the clusters and the red search failure curve: successful-search cost is unchanged, but the failed search is cut off earlier. Finally, delete 40% of the keys using tombstones and backward-shift deletion, and compare the red curve with the theoretical dashed curve: with tombstones it follows the one of a full table, with backward-shift deletion, that of a table with 40% fewer keys.

Watch the curves. With chaining, both grow almost linearly in α\alpha. With linear probing, successful lookup remains reasonable, but unsuccessful lookup grows as 1/(1−α)21/(1-\alpha)^2: at α=0.5\alpha = 0.5 it costs 2.52.5 probes, and at α=0.9\alpha = 0.9 it costs 50.550.5. This is Knuth’s formula, one of the best-known results in the analysis of algorithms.

The exact proof is lengthy: it uses recurrences or generating functions, and Knuth gave it in a 1963 memorandum often cited as the origin of algorithm analysis. The cause, however, is visible and has a name: primary clustering. If a cluster contains LL consecutive occupied cells, any key landing inside it or immediately behind it ends up at its end and extends it by one. This happens with probability ≈L/m\approx L/m, which grows with LL. Large clusters grow faster and merge with their neighbors: the rich get richer. Compare this with uniform probing, where each key follows a random permutation of the cells, an ideal approximated by double hashing. There are no clusters, and it is easy to prove that unsuccessful lookup costs at most 1/(1−α)1/(1-\alpha):

Proof

Let XX be the number of probes. X≥iX \ge i requires the first i−1i - 1 probes to hit occupied cells. The first does so with probability n/mn/m; conditional on that, the second does so with probability (n−1)/(m−1)(n-1)/(m-1); and so on. Each factor is at most α\alpha, since n−jm−j≤nm\frac{n-j}{m-j} \le \frac{n}{m} when n≤mn \le m. Therefore P[X≥i]≤αi−1\Pr[X \ge i] \le \alpha^{i-1} and E[X]=∑i≥1P[X≥i]≤∑i≥1αi−1=11−α\E[X] = \sum_{i \ge 1}\Pr[X \ge i] \le \sum_{i \ge 1}\alpha^{i-1} = \frac{1}{1-\alpha}.

∎

At α=0.9\alpha = 0.9, uniform probing costs 1010 probes and linear probing 50.550.5. Why use linear probing rather than double hashing? Because it visits contiguous cells: a 64-byte cache line fetches 8 cells at once, and five consecutive probes cost almost the same as one. On real hardware, linear probing with α≤0.7\alpha \le 0.7 beats almost everything else. The crucial point is to keep α\alpha from approaching 11.

Robin Hood

An observation about linear probing with uniform hashing: the set of occupied cells does not depend on insertion order. Neither does the sum of displacements, the distances from keys to their home cells, which equals the sum of final positions minus the sum of home positions. Mean displacement is therefore the same for every order. What can change is how displacement is distributed among keys. This is where Robin Hood hashing (Celis, 1986) comes in: during insertion, if the probing key has traveled farther than the cell’s resident, it takes the cell and the resident continues looking for a place (‘rob the rich to give to the poor’). Within each cluster, keys remain ordered by home cell. This gives two advantages: displacement variance is minimal, and an unsuccessful lookup can stop as soon as it encounters a resident with less displacement than the search itself, without waiting for an empty cell. In the figure, Robin Hood’s red curve becomes almost identical to the successful-lookup curve. Rust used this technique in HashMap until version 1.36 (2019), when it switched to hashbrown, a variant of Google’s Swiss tables.

Deleting without breaking searches

With open addressing, you cannot simply empty the cell of a deleted key: another key that passed through it during insertion would become unreachable, because lookup stops at the first empty cell. There are two solutions. The first leaves a tombstone (tombstone): the cell is marked as deleted, lookups pass through it, and insertions can reuse it. This is simple, but tombstones still count as occupied. In the figure, deleting 40% of the keys this way leaves the unsuccessful-lookup curve where it was, as though nothing had been deleted. Periodic rebuilding removes the tombstones. The second solution is backward shift deletion (Knuth’s algorithm R): empty the cell, then traverse subsequent cells, moving each key backward when doing so brings it closer to its home cell, until reaching an empty cell. This leaves no trace: the table behaves as though the key had never been inserted.

Universal hashing

So far we have assumed a hh satisfying the pairwise collision property. By the pigeonhole principle, a single fixed hash function cannot satisfy it for all pairs. A family can, because the probability concerns the choice of hh within that family:

The quantifier is crucial: for every pair, rather than ‘for most pairs’ or ‘for a random pair’. Look at the figure: it is a heat map of the small universe {0,…,p−1}\{0, \dots, p-1\}, where each cell (x,y)(x, y) gives the exact collision probability, calculated by enumerating the entire family.

InteractiveWhat does 'universal' mean?
Probability of collision for each pair of keys
key ykey x
Number of pairs at each ratio P/(1/m)\Pr / (1/m)
4200≤ 0.5≤ 0.8≤ 1≤ 1.5≤ 345> 3
Universality means the whole histogram is blue: no ratio exceeds 11.
Family of functions
h(x)=x mod mh(x) = x \bmod m
Sizes
Universe {0,…,p−1}\{0, \dots, p-1\}
8
Random draws
Exact Pr[h(3) = h(11)]1.0000
Universal bound 1/m1/m0.1250
Pairs that exceed 1/m1/m45 of 465
Maximum pairwise collision probability1.0000
Frequency in 0 drawsnot yet sampled
With a single function, there are 45 pairs of 465 that collide with probability 1: all keys congruent modulo mm. Whoever knows the function picks them and always wins.
Start with a fixed function, h(x)=x mod mh(x) = x \bmod m: the red stripes are pairs that always collide (those congruent modulo mm) and the adversary picks them at will. Move to the family without the term bb, ha(x)=(ax mod p) mod mh_a(x) = (ax \bmod p) \bmod m, and see how the stripes blur but pairs above 1/m1/m survive: without bb, the collision probability of (x,y)(x, y) only depends on the quotient yx−1 mod py x^{-1} \bmod p, and with p=31p = 31 and m=8m = 8 there are 240 pairs above 1/81/8; the worst, those of y≡5xy \equiv 5x, 7x7x, 9x9x, or 25x(modp)25x \pmod p, collide with probability 0.20.2. With Carter-Wegman, the map is one color: all pairs collide with the same probability and none exceed 1/m1/m. Pick 200 functions and compare the frequency with the exact value. Change mm to see how much slack there is.

The Carter and Wegman family

The classical family uses a prime p≥∣U∣p \ge \abs{U} (for example, p=261−1p = 2^{61} - 1 for 60-bit keys) and two random parameters:

ha,b(x)=((ax+b) mod p) mod m,a∈{1,…,p−1}, b∈{0,…,p−1}.h_{a,b}(x) = \big((ax + b) \bmod p\big) \bmod m, \qquad a \in \{1, \dots, p-1\},\ b \in \{0, \dots, p-1\}.
Proof

Fix x≠yx \neq y in {0,…,p−1}\{0, \dots, p-1\} and consider the pair (r,s)=(ax+b mod p, ay+b mod p)(r, s) = (ax + b \bmod p,\ ay + b \bmod p). Since r−s≡a(x−y)(modp)r - s \equiv a(x - y) \pmod p, with a≢0a \not\equiv 0 and x−y≢0x - y \not\equiv 0, we obtain r≠sr \neq s. Here primality of pp matters: x−yx - y and pp are coprime, so Bézout’s identity gives x−yx - y an inverse modulo pp. Conversely, from an ordered pair (r,s)(r, s) with r≠sr \neq s we recover the nonzero value a≡(r−s)(x−y)−1a \equiv (r - s)(x - y)^{-1} and b≡r−axb \equiv r - ax. Thus the map (a,b)↦(r,s)(a, b) \mapsto (r, s) is a bijection between the p(p−1)p(p-1) parameter pairs and the p(p−1)p(p-1) ordered pairs (r,s)(r, s) with r≠sr \neq s, using only modular arithmetic.

A collision occurs if and only if r≡s(modm)r \equiv s \pmod m. For each fixed rr, there are at most ⌈p/m⌉−1≤(p−1)/m\lceil p/m \rceil - 1 \le (p - 1)/m values s≠rs \neq r satisfying s≡r(modm)s \equiv r \pmod m. Consequently at most p(p−1)/mp(p-1)/m of the p(p−1)p(p-1) pairs (r,s)(r, s) collide, so the probability is at most 1/m1/m. Since the count depends on neither xx nor yy, it is identical for every pair.

∎

Three comments. First, sampling costs two integers: the family contains p(p−1)≈∣U∣2p(p-1) \approx \abs{U}^2 functions, so choosing one requires about 2log⁡2∣U∣2\log_2 \abs{U} random bits. Second, universal does not mean collision-free: the theorem controls only the expectation. With 2000 keys that are multiples of 10241024 in 4096 buckets, the number of colliding pairs ranges from 00 to thousands depending on the sampled function, as the code will show. The expectation is close to the bound of 488488 pairs, but the range is enormous. Third, the guarantee requires keys to be fixed without information about hh. An adversary observing the table, for example through timing, can gradually learn the function and then choose colliding keys. The complete defense in the adversary section therefore requires more than universality.

The chaining theorem requires only the pairwise collision property, so it applies to every universal family, not just Carter-Wegman. Three consequences follow immediately. The expected chaining cost is established; the probability that nn keys have any collision is at most (n2)/m\binom{n}{2}/m by the union bound; and with m≥n2m \ge n^2 this probability is less than 1/21/2. A quadratic-sized table therefore yields a table without collisions in two attempts in expectation by repeatedly sampling functions until none collide, a Las Vegas algorithm. This is the starting point of perfect hashing.

k-wise independence

Universality asks only that two keys almost never collide. Other schemes require more, and independence provides the appropriate language.

kk-wise independence implies (k−1)(k-1)-wise independence, and 2-wise independence implies universality. It is much stronger: it specifies the joint distribution of every pair, rather than just its collision probability. A natural example uses polynomials: if h(x)=(ck−1xk−1+⋯+c1x+c0) mod ph(x) = (c_{k-1}x^{k-1} + \dots + c_1 x + c_0) \bmod p with coefficients uniform in {0,…,p−1}\{0, \dots, p-1\}, the family is kk-wise independent as functions into {0,…,p−1}\{0, \dots, p-1\}. For kk distinct points x1,…,xkx_1, \dots, x_k, the map from coefficients to the kk values is a bijection: its matrix is a Vandermonde matrix whose determinant is ∏i<j(xj−xi)≠0\prod_{i<j}(x_j - x_i) \ne 0 modulo pp. The values are therefore uniform and independent. Each evaluation costs k−1k - 1 multiplications.

How much independence does each algorithm need?

SchemeRequired guaranteeReference
Chaining, expectation of an operationuniversality (2 to 2)Carter and Wegman, 1979
Two-level perfect hashing (FKS)universalityFredman, Komlós and Szemerédi, 1984
Linear probing, O(1)\bigO(1) expected for operation5-independence is enough; 4 noPagh, Pagh and Ružić, 2007; Pătraşcu and Thorup, 2010
Cuckoo, success with probability 1−O(1/n)1 - \bigO(1/n)functions O(log⁡n)\bigO(\log n)-independent in the original analysisPagh and Rodler, 2004

The linear-probing row is the surprising one. Universality, and even 4-wise independence, is not enough: there are 4-wise independent families for which a linear-probing operation costs Ω(log⁡n)\Omega(\log n) in expectation, whereas 5-wise independence recovers O(1)\bigO(1). See Thorup’s notes on fast hashing. The underlying reason is that analyzing a cluster involves the joint behavior of many keys at once, rather than pairs.

Simple tabulation

There is a particularly inexpensive way to obtain these guarantees without evaluating a polynomial. Split a 32-bit key into four 8-bit characters, x=(x0,x1,x2,x3)x = (x_0, x_1, x_2, x_3), fill four tables with 256 random words each, T0,…,T3T_0, \dots, T_3, and define

h(x)=T0[x0]⊕T1[x1]⊕T2[x2]⊕T3[x3].h(x) = T_0[x_0] \oplus T_1[x_1] \oplus T_2[x_2] \oplus T_3[x_3].

This requires four reads from a small cache and three XOR operations. It is Zobrist hashing (1970), which chess programs use to identify positions: assign a random number to each piece-square pair, then XOR the numbers for all pieces present. Pătraşcu and Thorup (2012) proved a remarkable result: simple tabulation is only 3-wise independent, but behaves almost like fully random hashing for linear probing, cuckoo hashing, and other applications. Its limitation is visible in one line: if xx and yy differ in two characters, the hashes of the four keys forming a rectangle XOR to zero, so the family is not 4-wise independent. You will implement it in an exercise.

Perfect hashing: the two-level table

If the key set SS is static, such as a vocabulary, a language’s reserved words, or a dictionary built once and queried millions of times, you can obtain something an ordinary dynamic table does not provide: O(1)\bigO(1) lookup in the worst case with O(n)\bigO(n) space. This is perfect hashing. The construction of Fredman, Komlós and Szemerédi (1984) uses only universal hashing:

  1. First level. A universal function hh distributes the nn keys across m=nm = n buckets. Let nin_i be the number of keys in bucket ii.
  2. Second level. Bucket ii gets its own table of size ni2n_i^2 and its own universal function hih_i, repeatedly sampled until there are no collisions.

To look up kk, compute i=h(k)i = h(k) and inspect cell hi(k)h_i(k) of table ii: always two function evaluations and two accesses. The risk is that the quadratic tables might occupy too much space; the next proof controls this.

Proof

The identity ni2=ni+2(ni2)n_i^2 = n_i + 2\binom{n_i}{2} gives ∑ini2=n+2C\sum_i n_i^2 = n + 2C, where CC counts the key pairs colliding at the first level. Linearity of expectation and universality give E[C]≤(n2)/m=n−12\E[C] \le \binom{n}{2}/m = \frac{n-1}{2}, hence E[∑ini2]≤n+(n−1)=2n−1<2n\E[\sum_i n_i^2] \le n + (n-1) = 2n - 1 < 2n. For the second claim, the expected number of collisions among nin_i keys in a table of ni2n_i^2 cells is at most (ni2)/ni2<1/2\binom{n_i}{2}/n_i^2 < 1/2. By Markov’s inequality, the probability of any collision is less than 1/21/2.

∎

Applying Markov again gives P[∑ini2≥4n]<1/2\Pr[\sum_i n_i^2 \ge 4n] < 1/2. Simply retry the first level until ∑ini2<4n\sum_i n_i^2 < 4n, requiring fewer than two attempts in expectation, and retry each subtable until it is collision-free, again requiring fewer than two attempts in expectation each. This is a Las Vegas algorithm with expected time O(n)\bigO(n), expected space at most n+4nn + 4n cells plus the function parameters, and two-access lookup. Below, you will construct it and measure ∑ni2/n\sum n_i^2 / n, which comes out very close to 22.

Cuckoo hashing

FKS is static. Can we have worst-case lookup guarantees and insertions? Cuckoo hashing (Pagh and Rodler, 2001) achieves this with an idea inspired by the cuckoo, which lays its egg in another bird’s nest and evicts the occupant.

Use two tables, T1T_1 and T2T_2, each with rr cells, and two functions h1,h2h_1, h_2. The invariant is that every key xx occupies either T1[h1(x)]T_1[h_1(x)] or T2[h2(x)]T_2[h_2(x)]. Lookup checks exactly these two cells, giving two accesses in the worst case. Inserting xx places it in T1[h1(x)]T_1[h_1(x)]. If that cell is occupied, evict its resident yy to its other cell T2[h2(y)]T_2[h_2(y)], evicting any occupant there in turn, and continue. If the eviction chain reaches a free cell, insertion finishes. If it exceeds a maximum number of steps, a multiple of log⁡r\log r, abandon the attempt: draw two new functions and reinsert all keys.

InteractiveThe cuckoo dance
Table 1Table 2abcdef12b3e45d6f7a8123c45678
  • cycle-free component
  • a cycle (still fits)
  • two cycles (no fit)
Probability that nn random keys (Monte Carlo) will fit
  • r = 8
  • threshold 1/2
Insertions
Hash functions
Keys / cells6 / 16
Load factor37.5 %
Evictions of the last insertion0
Rebuilds0
Components with 1 cycle / with 2 or more1 / 0
Six keys are in place (37.5% load). Insert the next key and see whether its cell is empty or it evicts another key.
Two tables of 8 cells. Click «Insert key»: the orange key tries its cell in table 1 and, if it is occupied, the resident key moves to its other cell, and so on until a free cell is found. The lines are the keys (linking their two possible cells) and form a graph. Fill the table until 50% and continue inserting: at some point a component will have two cycles (red) and the insertion will enter a loop, and you have to rehash with new functions. The graph gives the probability that nn random keys fit: with r=8r = 8 the transition is smooth, with r=512r = 512 it is much more abrupt and starts at 50%; when r→∞r \to \infty it tends to a step at 50%.

The drawing also shows the graph that explains the mechanism. Its vertices are the 2r2r cells, and each key xx is an edge between T1[h1(x)]T_1[h_1(x)] and T2[h2(x)]T_2[h_2(x)]. Placing keys means orienting each edge toward its occupied cell, so that every cell receives at most one edge. In a connected component with vv vertices and ee edges, this is possible only if e≤ve \le v: the component must be a tree or contain a single cycle, which can be oriented around the cycle. With two cycles, there are more keys than cells and insertion loops indefinitely. The condition is exact: the nn keys fit if and only if every component of the cuckoo graph contains at most one cycle.

A classical result on random graphs now enters. With random hash functions, this is a random bipartite graph with 2r2r vertices and nn edges. In the Erdős-Rényi model with MM edges on NN vertices, M=N/2M = N/2 is the phase-transition threshold. Below it, components are small: trees and occasional isolated cycles, with probability O(1/N)\bigO(1/N) of a component containing two cycles. Above it, a giant component appears with many cycles. Here N=2rN = 2r, so the threshold is n=rn = r, a total load of 50%. This is what the figure’s plot shows.

A 50% load is low. The remedy is to give each key more choices: with d=3d = 3 functions the threshold rises to ≈91.8 %\approx 91.8\,\%, and with d=4d = 4 to ≈97.7 %\approx 97.7\,\%, according to work by Dietzfelbinger and colleagues and by Frieze and Melsted. High-performance implementations and cuckoo filters use several cells per bucket or more functions. Pagh and Rodler required O(log⁡n)\bigO(\log n)-wise independent functions; Pătraşcu and Thorup showed that simple tabulation suffices with a weaker failure bound. Evictions are inexpensive in practice: below, you will measure fewer than one eviction per insertion on average below 50% load.

When the attacker chooses the keys

Everything above assumes that keys are fixed before the function is sampled. This assumption breaks when whoever chooses the keys can see or infer the function. Hash flooding is an algorithmic complexity attack against hash tables: if the function is known and has no secret key, an attacker computes nn keys with the same hash and sends them. All reach the same bucket; each insertion traverses a longer chain, and total cost becomes Θ(n2)\Theta(n^2) instead of Θ(n)\Theta(n). A small request can keep a processor busy.

To see the mechanism without interacting with a real application, we use our own toy table and Java’s polynomial string hash, h(s)=∑isi⋅31L−1−i mod 232h(s) = \sum_i s_i \cdot 31^{L-1-i} \bmod 2^{32}. Its known weakness is sufficient: the strings ‘Aa’ and ‘BB’ share a hash, 65⋅31+97=66⋅31+66=211265 \cdot 31 + 97 = 66 \cdot 31 + 66 = 2112. Because the hash is polynomial, concatenating equal-length blocks of these strings preserves equality. With kk blocks, this produces 2k2^k distinct strings with exactly the same 32-bit hash. The figure compares three functions on ordinary and constructed keys.

InteractiveFlood the table
Chain lengths with fixed polynomial: number of buckets of each length
11010010002.0k012345678-1516-3132-631≥64chain length (red bars: 8 or more)
Cumulative comparisons against nn (log axes)
  • fixed polynomial
  • secret base
  • SipHash-2-4
  • n²/2
Hash function of the table
Keys that arrive
1024
100 %
Key comparisons523776
Per insertion (mean)511.5
Longest chain1024
Ratio to n(n−1)/2n(n-1)/21.000
Table size2048 buckets
The 1024 crafted keys have the same 32-bit hash, so they fall into the same bucket regardless of the table size: 523776 comparisons, exactly n(n−1)/2n(n-1)/2.
Choose the hash function and the type of keys. With the fixed polynomial and fabricated keys, all fall into the same bucket: in the histogram, all buckets are empty except one, the red bar at the end, which holds the nn keys, and the red curve of comparisons rises with a slope of 22 on logarithmic axes. Switch to a secret base or to SipHash: the crafted keys (built against the fixed function) behave like ordinary keys, and the curve returns to being almost like that of the legitimate keys. Lower the part of malicious traffic: a minority is enough to pay k(k−1)/2k(k-1)/2 comparisons for their kk keys. Press «New secret key»: the numbers barely change, and that is the idea.

Defenses

  1. A secret key per process. This is what universal hashing provides, changing the game: the attacker constructs keys before the server samples its function, so each pair collides with probability at most 1/m1/m under a random function. For strings, a guaranteed variant uses a polynomial hash modulo a prime pp with a random secret base. Two distinct strings of length at most LL collide with probability at most (L−1)/p(L-1)/p when the base is uniform in {0,…,p−1}\{0, \dots, p-1\}, because their difference is a nonzero polynomial in the base of degree less than LL, with at most L−1L-1 roots. Nonzero here requires either that no character has value 00 or that length enters the hash; otherwise "a" and "\x00a" yield the same polynomial. With p=261−1p = 2^{61} - 1 and 100-character strings, the bound is less than 5⋅10−175 \cdot 10^{-17}.
  2. Make the key truly secret: a PRF. Adding a random prefix and suffix to a fast hash, Python’s initial response in version 3.3 (2012), was insufficient. Aumasson and Bernstein (2012) showed that seeding a fast noncryptographic hash is insufficient: one can construct seed-independent collisions or recover the seed by observing the table. They proposed SipHash, a pseudorandom function with a 128-bit key whose output cannot be distinguished from uniform without knowing the key. PEP 456 adopted it in Python 3.4 for str and bytes.
  3. Bound the work. Limiting the number of request parameters or the body size keeps nn small. This was the quickest mitigation after the December 2011 disclosure: PHP 5.3.9 introduced max_input_vars in January 2012. Converting long buckets into balanced trees also limits a chain’s cost to O(log⁡n)\bigO(\log n). Java 8’s HashMap does this for buckets with more than 8 entries, provided keys are comparable. The next lesson on ordered structures explains how.
  4. Detect. With α≤0.75\alpha \le 0.75 and a good hash function, a bucket longer than about 8 keys is extremely rare. Monitoring maximum chain or probe length and alerting when it spikes provides an inexpensive signal of an attack or a poor function.

CPython remains a warning that defenses have boundaries: it randomizes str and bytes, but not integers or tuples of integers. On a 64-bit build, an integer’s hash is its remainder modulo the Mersenne prime 261−12^{61} - 1, so that integer and all its multiples have hash 00. If dictionary integer keys come from a third party, the cost can become quadratic again. You will measure this on your own table, without targeting anyone.

CPython dictionaries

CPython’s dict combines almost everything discussed here. It uses open addressing rather than lists, with a power-of-two size. Since Python 3.6, with ordering guaranteed since 3.7, it has used a compact layout proposed by Raymond Hettinger in 2012, implemented earlier in PyPy and implemented in CPython 3.6 by Inada Naoki:

  • An index array of mm small cells, occupying 1, 2, 4 or 8 bytes depending on mm. Positions are indexed by hash, and each cell stores either ‘empty’, ‘tombstone’, or an entry number.
  • A dense array of (hash, clave, valor) entries in insertion order. This is why a dict remembers order and iteration traverses a contiguous array without jumps.

The probe sequence is not linear. It starts at i=h∧(m−1)i = h \wedge (m-1) and advances using i←(5i+perturb+1) mod mi \leftarrow (5i + \text{perturb} + 1) \bmod m, where perturb\text{perturb} initially holds the entire hash as an unsigned 64-bit integer and shifts right by 5 bits at every step. Modulo a power of two, the recurrence i↦5i+1i \mapsto 5i + 1 is a congruential generator of full period by the Hull-Dobell theorem: the increment is odd and the multiplier is ≡1 mod 4\equiv 1 \bmod 4. It therefore eventually visits every cell, even after perturbation runs out. Perturbation gradually introduces high hash bits that h∧(m−1)h \wedge (m-1) alone would ignore. Hashes with identical low bits but different high bits diverge once the 5-bit shifts bring their differing bits into the mix, at the fifth probe in the example below, where they differ at bit 20. When the table reaches 2/32/3 occupancy, counting tombstones, it is rebuilt to about three times the number of entries, rounded to a power of two, which removes tombstones. You can verify all of this:

[ ]The probing sequence and dict rebuild pointsBrowser
import sys, random

def secuencia_sondeo(h, tam, cuantos):
    """Celdas que visita CPython para un hash h en una tabla de índices de tamaño tam (potencia de 2)."""
    mask, perturb = tam - 1, h & ((1 << 64) - 1)       # el hash se trata como entero sin signo de 64 bits
    i, out = h & mask, []
    for _ in range(cuantos):
        out.append(i)
        perturb >>= 5
        i = (5 * i + perturb + 1) & mask
    return out

# mismos bits bajos, distintos bits altos: las secuencias coinciden al principio y divergen cuando entra la perturbación
print("hash = 3:         ", secuencia_sondeo(3, 8, 8))
print("hash = 3 + 2^20:  ", secuencia_sondeo(3 + 2**20, 8, 8))

# periodo completo: ningún hash deja celdas sin visitar
rng = random.Random(0)
for tam in (8, 64, 1024):
    malos = sum(len(set(secuencia_sondeo(rng.getrandbits(64), tam, 40 * tam))) < tam for _ in range(300))
    print(f"tabla de {tam:5d}: {malos} de 300 hashes no llegan a visitar todas las celdas")

# puntos de reconstrucción: el tamaño del diccionario cambia cuando se llena 2/3 de la tabla de índices
d, ultimo, saltos = {}, sys.getsizeof({}), []
for n in range(1, 700):
    d[n] = n
    s = sys.getsizeof(d)
    if s != ultimo:
        saltos.append(n)
        ultimo = s
print("\nel diccionario cambia de tamaño al insertar el elemento nº", saltos, " (el 1 es la primera reserva: un dict vacío no tiene tabla propia)")
print("predicción (2/3 de 8, 16, 32, ... más uno):", [(2 * 2**k) // 3 + 1 for k in range(3, 11)])

A relevant design detail: the index table’s maximum load is 2/32/3, so it never approaches the region where linear probing becomes expensive. Perturbation eliminates primary clustering without double hashing. Sets, set, use a similar scheme with a small linear-probing window before perturbation jumps, to take advantage of the cache.

Implementation from scratch

We begin with the Carter-Wegman family and its empirical test, followed by the other two functions introduced above: multiply-shift hashing and the fixed function against which the adversary chooses keys.

[ ]Universal families: what they guarantee and what they do notBrowser
import random
from collections import Counter

P = (1 << 61) - 1                              # primo de Mersenne

class Universal:
    """Carter y Wegman: h(x) = ((a x + b) mod p) mod m, con a en [1, p-1] y b en [0, p-1]."""
    def __init__(self, m, rng):
        self.m, self.a, self.b = m, rng.randrange(1, P), rng.randrange(P)
    def __call__(self, x):
        return ((self.a * x + self.b) % P) % self.m

class MultiplicaDesplaza:
    """h(x) = (a x mod 2^64) >> (64 - l), con a impar: m = 2^l cubetas, sin divisiones. Colisión con probabilidad <= 2/m."""
    def __init__(self, l, rng):
        self.m, self.l, self.a = 1 << l, l, rng.randrange(1, 1 << 64, 2)
    def __call__(self, x):
        return ((self.a * x) & ((1 << 64) - 1)) >> (64 - self.l)

class Modulo:
    """Una sola función, sin aleatoriedad: x mod m."""
    def __init__(self, m):
        self.m = m
    def __call__(self, x):
        return x % self.m

rng = random.Random(4)
m = 64
x, y = 12345, 12345 + 64 * 1000                # congruentes módulo 64: la función fija los hace colisionar siempre
fabricas = {"x mod m (fija)": lambda: Modulo(m),
            "Carter-Wegman": lambda: Universal(m, rng),
            "multiplicar-desplazar": lambda: MultiplicaDesplaza(6, rng)}
for nombre, fab in fabricas.items():
    N = 20000
    colisiones = sum(h(x) == h(y) for h in (fab() for _ in range(N)))
    print(f"{nombre:22s} Pr[h(x) = h(y)] ≈ {colisiones / N:.4f}   (1/m = {1 / m:.4f}, 2/m = {2 / m:.4f})")

# claves estructuradas: 2000 direcciones alineadas a 1024 en una tabla de 4096 cubetas
claves = [1024 * i for i in range(2000)]
m = 4096
def pares(h):
    return sum(c * (c - 1) // 2 for c in Counter(h(k) for k in claves).values())
print(f"\npares que colisionan entre {len(claves)} claves múltiplos de 1024, m = {m} (cota n(n-1)/(2m) = {len(claves) * (len(claves) - 1) // 2 // m}):")
for nombre, fab in [("x mod m (fija)", lambda: Modulo(m)),
                    ("Carter-Wegman", lambda: Universal(m, rng)),
                    ("multiplicar-desplazar", lambda: MultiplicaDesplaza(12, rng))]:
    v = [pares(fab()) for _ in range(40)]
    print(f"  {nombre:22s} media {sum(v) / len(v):9.1f}   mínimo {min(v):6d}   máximo {max(v):6d}")

Notice both findings. The fixed function always collides on the chosen pair, while the two randomized functions collide with frequency close to 1/m1/m for every pair, not just this one. Yet with structured keys, the number of colliding pairs ranges from zero to thousands across functions: universality controls the expectation, not dispersion. The x mod m function is excellent on random keys and disastrous on aligned addresses.

Now implement the chained table, with a new function at every rebuild:

[ ]Chaining with universal functionsBrowser
class Encadenada:
    """Tabla con encadenamiento; se duplica cuando n > m (factor de carga <= 1)."""
    def __init__(self, rng, m=8):
        self.rng, self.m, self.n = rng, m, 0
        self.h = Universal(m, rng)
        self.cub = [[] for _ in range(m)]
        self.sondeos = 0                          # nodos examinados en total
    def _reconstruir(self, m):
        viejas = [k for c in self.cub for k in c]
        self.m, self.h = m, Universal(m, self.rng)
        self.cub = [[] for _ in range(m)]
        for k in viejas:
            self.cub[self.h(k)].append(k)
    def buscar(self, k):
        for x in self.cub[self.h(k)]:
            self.sondeos += 1
            if x == k:
                return True
        return False
    def insertar(self, k):
        if self.buscar(k):
            return
        if self.n >= self.m:
            self._reconstruir(2 * self.m)
        self.cub[self.h(k)].append(k)
        self.n += 1
    def borrar(self, k):
        c = self.cub[self.h(k)]
        if k in c:
            c.remove(k)
            self.n -= 1

rng = random.Random(7)
t = Encadenada(rng)
claves = rng.sample(range(10**9), 5000)
for k in claves:
    t.insertar(k)
alfa = t.n / t.m
print("m =", t.m, " n =", t.n, " alfa =", round(alfa, 3), " cadena máxima:", max(map(len, t.cub)))
t.sondeos = 0
for k in claves:
    t.buscar(k)
print("sondeos medios con éxito:", round(t.sondeos / len(claves), 3), "  teoría 1 + alfa/2 =", round(1 + alfa / 2, 3))
t.sondeos = 0
for k in claves:
    t.buscar(k + 10**9)                           # ausentes
print("sondeos medios fallidos :", round(t.sondeos / len(claves), 3), "  teoría alfa =", round(alfa, 3))

Open addressing with linear probing, Robin Hood insertion, and backward shift deletion fits in a single class: each cell stores a key and its displacement. Randomized tests validate it against a set, and its costs are compared with Knuth’s formula.

[ ]Linear probing and Robin Hood with backward-shift deletionBrowser
VACIA = None

class Abierta:
    """Sondeo lineal. Con robin=True, Robin Hood: se queda la celda quien más lejos está de su origen.
    Cada celda guarda (clave, distancia al origen). El borrado desplaza hacia atrás (sin lápidas)."""
    def __init__(self, m, rng, robin=False):
        self.m, self.robin, self.n = m, robin, 0
        self.h = Universal(m, rng)
        self.celdas = [VACIA] * m

    def insertar(self, k):
        assert self.n < self.m - 1, "tabla llena"
        i, d, item = self.h(k), 0, k
        while True:
            c = self.celdas[i]
            if c is VACIA:
                self.celdas[i] = (item, d)
                self.n += 1
                return
            if c[0] == item:
                return                                   # ya estaba
            if self.robin and c[1] < d:                  # el residente está más cerca de su origen: me quedo su celda
                self.celdas[i] = (item, d)
                item, d = c[0], c[1]
            i = (i + 1) % self.m
            d += 1

    def buscar(self, k):
        """Devuelve (encontrada, sondeos)."""
        i, d, s = self.h(k), 0, 0
        while True:
            s += 1
            c = self.celdas[i]
            if c is VACIA or (self.robin and c[1] < d):
                return False, s
            if c[0] == k:
                return True, s
            i = (i + 1) % self.m
            d += 1

    def borrar(self, k):
        i, d = self.h(k), 0
        while True:
            c = self.celdas[i]
            if c is VACIA or (self.robin and c[1] < d):
                return False
            if c[0] == k:
                break
            i = (i + 1) % self.m
            d += 1
        j = i                                             # desplazamiento hacia atrás
        while True:
            self.celdas[i] = VACIA
            while True:
                j = (j + 1) % self.m
                cj = self.celdas[j]
                if cj is VACIA:
                    self.n -= 1
                    return True
                if cj[1] >= (j - i) % self.m:             # su origen no está entre i (excluido) y j: puede subir a i
                    break
            self.celdas[i] = (cj[0], cj[1] - (j - i) % self.m)
            i = j

# prueba aleatoria frente a un set: inserciones y borrados mezclados
rng = random.Random(3)
for robin in (False, True):
    t, ref = Abierta(256, rng, robin), set()
    for paso in range(20000):
        k = rng.randrange(400)
        if rng.random() < 0.5 and len(ref) < 200:
            t.insertar(k)
            ref.add(k)
        else:
            assert t.borrar(k) == (k in ref)
            ref.discard(k)
        if paso % 500 == 0:
            assert all(t.buscar(x)[0] == (x in ref) for x in range(400))
    print("Robin Hood" if robin else "lineal    ", "coincide con set tras 20000 operaciones, n =", t.n)

def fallo_desde(t, i):
    """Sondeos de una búsqueda fallida que empieza en la celda i (sin necesitar una clave concreta)."""
    d = s = 0
    while True:
        s += 1
        c = t.celdas[i]
        if c is VACIA or (t.robin and c[1] < d):
            return s
        i = (i + 1) % t.m
        d += 1

def curva(robin, alfa, m=2048, tablas=8):
    exito = fallo = 0.0
    for s in range(tablas):
        r = random.Random(100 + s)
        t = Abierta(m, r, robin)
        claves = r.sample(range(10**9), int(alfa * m))
        for k in claves:
            t.insertar(k)
        exito += sum(t.buscar(k)[1] for k in claves) / len(claves)
        fallo += sum(fallo_desde(t, i) for i in range(m)) / m     # promedio exacto sobre las m celdas de origen
    return exito / tablas, fallo / tablas

print(f"{'alfa':>5} {'éxito lin':>10} {'(Knuth)':>8} {'fallo lin':>10} {'(Knuth)':>8} {'éxito RH':>9} {'fallo RH':>9}")
for alfa in (0.5, 0.8, 0.9):
    sl, fl = curva(False, alfa)
    sr, fr = curva(True, alfa)
    print(f"{alfa:5.2f} {sl:10.2f} {(1 + 1/(1-alfa))/2:8.2f} {fl:10.2f} {(1 + 1/(1-alfa)**2)/2:8.2f} {sr:9.2f} {fr:9.2f}")

Successful lookup costs are identical in both variants because mean displacement is the same, as explained above. Robin Hood makes unsuccessful lookup much cheaper: at α=0.9\alpha = 0.9 it costs about 5.45.4 probes rather than linear probing’s 3838. Knuth’s formula is asymptotic, m→∞m \to \infty; here we use eight 2048-cell tables per point. Agreement is excellent at α=0.5\alpha = 0.5, differs by 12% at α=0.8\alpha = 0.8 (11.411.4 versus 1313), and at α=0.9\alpha = 0.9 theory gives 50.550.5, well above the measured 37.637.6. This is not an error: two effects combine. First, finite size. Knuth also gives the exact formula for mm cells and nn keys, 12(1+∑k≥0(k+1)n(n−1)⋯(n−k+1)mk)\frac12\big(1 + \sum_{k \ge 0} (k+1)\frac{n(n-1)\cdots(n-k+1)}{m^k}\big). With m=2048m = 2048 and n=1843n = 1843 it gives 45.045.0, rather than 50.550.5; at α=0.8\alpha = 0.8 it gives 12.612.6. Convergence to the limit is slow as α\alpha approaches 11. Second, dispersion: large clusters are rare but very costly, so mean unsuccessful-lookup cost varies greatly across tables, and an average over eight tables often undershoots the expectation. The figure, using 1024-cell tables and three seeds, shows the same behavior: at α=0.9\alpha = 0.9 the exact expectation is 40.840.8, and at 0.950.95 it is 109109, rather than the limiting 50.550.5 and 200.5200.5. The measured red curve lies below the theoretical curve. Next comes cuckoo hashing.

[ ]Cuckoo hashing with rehashingBrowser
import math

class Cuckoo:
    """Dos tablas de r celdas y dos funciones hash. Una clave vive en t[0][h0(k)] o en t[1][h1(k)]."""
    def __init__(self, r, rng):
        self.r, self.rng, self.n = r, rng, 0
        self.reconstrucciones = self.desalojos = 0
        self._nuevas()
    def _nuevas(self):
        self.h = (Universal(self.r, self.rng), Universal(self.r, self.rng))
        self.t = ([None] * self.r, [None] * self.r)
    def buscar(self, k):                                # como mucho dos accesos
        return self.t[0][self.h[0](k)] == k or self.t[1][self.h[1](k)] == k
    def _colocar(self, k):
        """Inserta con desalojos; devuelve la clave que quedó sin sitio (None si todo fue bien)."""
        tope = 6 * (int(math.log2(self.r)) + 1)         # MaxLoop ~ 6 log r
        j = 0
        for _ in range(tope):
            i = self.h[j](k)
            k, self.t[j][i] = self.t[j][i], k           # la clave entra y desaloja a la que había
            if k is None:
                return None
            self.desalojos += 1
            j = 1 - j                                   # la desalojada va a su otra tabla
        return k
    def insertar(self, k):
        if self.buscar(k):
            return
        suelta = self._colocar(k)
        self.n += 1
        if suelta is not None:                          # ciclo: nuevas funciones y reinserción de todo
            claves = [x for tb in self.t for x in tb if x is not None] + [suelta]
            for _ in range(30):
                self.reconstrucciones += 1
                self._nuevas()
                if all(self._colocar(x) is None for x in claves):
                    return
            raise RuntimeError("no cabe: carga demasiado alta para dos funciones")

rng = random.Random(11)
r = 512
print(f"{'carga':>6} {'n':>5} {'sin reconstruir':>16} {'desalojos / inserción':>22} {'no cabe':>8}")
for carga in (0.30, 0.45, 0.50, 0.55, 0.60):
    n, sin_rec, desal, nocabe = int(carga * 2 * r), 0, 0, 0
    for ensayo in range(20):
        t = Cuckoo(r, rng)
        try:
            for k in rng.sample(range(10**9), n):
                t.insertar(k)
            sin_rec += t.reconstrucciones == 0
            desal += t.desalojos
        except RuntimeError:
            nocabe += 1
    print(f"{carga:6.2f} {n:5d} {sin_rec:13d}/20 {desal / max(1, (20 - nocabe) * n):22.2f} {nocabe:8d}")

Below 50% load, there are no rebuilds and mean evictions per insertion stay below one. At 50%, four of twenty trials required rebuilding; at 55%, twelve did; at 60%, eighteen did, with eight evictions per insertion on average. The random-graph transition is visible even with r=512r = 512. Each rebuild is a Las Vegas retry. With r=512r = 512 and loads slightly above 50%, a suitable pair of functions can still appear after a few retries. However, a single attempt’s success probability tends to zero as rr grows, as the figure shows: above the threshold, rebuilding ceases to solve the problem and the table must grow.

Finally, FKS. The class is small because the analysis does most of the work: the measured ∑ini2/n\sum_i n_i^2 / n is close to 22.

[ ]Two-level perfect hashing (FKS)Browser
class FKS:
    """Diccionario estático con búsqueda en O(1) en el peor caso: dos niveles de funciones universales."""
    def __init__(self, claves, rng):
        claves = set(claves)
        n = len(claves)
        self.intentos1 = 0
        while True:                                        # nivel 1: reintentar hasta que sum n_i^2 < 4n
            self.intentos1 += 1
            self.h = Universal(n, rng)
            grupos = [[] for _ in range(n)]
            for k in claves:
                grupos[self.h(k)].append(k)
            self.suma_cuadrados = sum(len(g) ** 2 for g in grupos)
            if self.suma_cuadrados < 4 * n:
                break
        self.intentos2 = 0
        self.sub = []                                      # nivel 2: tabla de tamaño n_i^2 sin colisiones
        for g in grupos:
            m2 = max(1, len(g) ** 2)
            while True:
                self.intentos2 += 1
                h2 = Universal(m2, rng)
                tabla = [None] * m2
                ok = True
                for k in g:
                    j = h2(k)
                    if tabla[j] is not None:
                        ok = False
                        break
                    tabla[j] = k
                if ok:
                    break
            self.sub.append((h2, tabla))
        self.celdas = n + sum(len(t) for _, t in self.sub)
    def __contains__(self, k):                             # dos funciones hash y dos accesos, siempre
        h2, tabla = self.sub[self.h(k)]
        return tabla[h2(k)] == k

rng = random.Random(5)
print(f"{'n':>6} {'sum n_i^2 / n':>14} {'intentos nivel 1':>17} {'intentos nivel 2 / n':>21} {'celdas / n':>11}")
for n in (500, 2000, 6000):
    claves = list({rng.getrandbits(40) for _ in range(n)})
    f = FKS(claves, rng)
    presentes = set(claves)
    assert all(k in f for k in claves) and not any((k + 1) in f for k in claves if (k + 1) not in presentes)
    print(f"{n:6d} {f.suma_cuadrados / n:14.3f} {f.intentos1:17d} {f.intentos2 / n:21.3f} {f.celdas / n:11.3f}")

Attack and defense in miniature

We reproduce the figure’s mechanism with a toy table that counts key comparisons. The first experiment constructs colliding keys for the unkeyed polynomial hash and measures the degradation. It targets our own table, like a load test: the purpose is to understand the failure and write tests that detect it.

[ ]Hash flooding against a toy tableBrowser
def hash_poli(s, base=31, mod=1 << 32):
    """Hash polinómico (Horner) sin clave: el de String.hashCode de Java si base = 31 y mod = 2^32."""
    h = 0
    for c in s:
        h = (h * base + ord(c)) % mod
    return h

def colisionan(k):
    """2^k cadenas distintas con el mismo hash polinómico: «Aa» y «BB» valen lo mismo, y los bloques se concatenan."""
    bloques = ("Aa", "BB")
    return ["".join(bloques[(i >> b) & 1] for b in range(k - 1, -1, -1)) for i in range(2 ** k)]

print("hash('Aa') =", hash_poli("Aa"), "  hash('BB') =", hash_poli("BB"))
cs = colisionan(4)
print(len(cs), "claves distintas,", len({hash_poli(c) for c in cs}), "valor de hash distinto:", cs[:3], "...")

class TablaEncadenada:
    """Tabla de juguete con encadenamiento; cuenta las comparaciones de claves."""
    def __init__(self, m, hash_fn):
        self.m, self.f = m, hash_fn
        self.cub = [[] for _ in range(m)]
        self.comparaciones = 0
    def insertar(self, k):
        c = self.cub[self.f(k) % self.m]
        for x in c:
            self.comparaciones += 1
            if x == k:
                return
        c.append(k)
    def mas_larga(self):
        return max(len(c) for c in self.cub)

def coste(claves, hash_fn):
    t = TablaEncadenada(1 << 13, hash_fn)
    for k in claves:
        t.insertar(k)
    return t.comparaciones, t.mas_larga()

rng = random.Random(1)
aleatorias = lambda n: ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(22)) for _ in range(n)]
print(f"\n{'n':>6} {'legítimas':>11} {'fabricadas':>11} {'n(n-1)/2':>10}   cadena más larga (fabricadas)")
for k in (8, 9, 10, 11):
    n = 2 ** k
    c_ok, _ = coste(aleatorias(n), hash_poli)
    c_mal, largo = coste(colisionan(k), hash_poli)
    print(f"{n:6d} {c_ok:11d} {c_mal:11d} {n * (n - 1) // 2:10d}   {largo}")

With ordinary keys, cost is almost linear. With constructed keys, it equals n(n−1)/2n(n-1)/2 exactly: doubling nn quadruples the cost. We implement the defense, SipHash-2-4, from scratch in about twenty lines and validate it against the original paper’s test vector.

[ ]SipHash-2-4 from scratch and the defenseBrowser
M64 = (1 << 64) - 1

def rotl(x, b):
    return ((x << b) | (x >> (64 - b))) & M64

def siphash24(msg: bytes, key: bytes) -> int:
    """SipHash-2-4 (Aumasson y Bernstein, 2012): una PRF con clave de 128 bits sobre mensajes cortos."""
    k0, k1 = int.from_bytes(key[:8], "little"), int.from_bytes(key[8:], "little")
    v0, v1 = k0 ^ 0x736f6d6570736575, k1 ^ 0x646f72616e646f6d
    v2, v3 = k0 ^ 0x6c7967656e657261, k1 ^ 0x7465646279746573
    def ronda(v0, v1, v2, v3):
        v0 = (v0 + v1) & M64; v1 = rotl(v1, 13) ^ v0; v0 = rotl(v0, 32)
        v2 = (v2 + v3) & M64; v3 = rotl(v3, 16) ^ v2
        v0 = (v0 + v3) & M64; v3 = rotl(v3, 21) ^ v0
        v2 = (v2 + v1) & M64; v1 = rotl(v1, 17) ^ v2; v2 = rotl(v2, 32)
        return v0, v1, v2, v3
    n = len(msg)
    for i in range(0, n - n % 8, 8):
        m = int.from_bytes(msg[i:i + 8], "little")
        v3 ^= m
        v0, v1, v2, v3 = ronda(v0, v1, v2, v3)
        v0, v1, v2, v3 = ronda(v0, v1, v2, v3)
        v0 ^= m
    ultimo = int.from_bytes(msg[n - n % 8:], "little") | ((n & 255) << 56)
    v3 ^= ultimo
    v0, v1, v2, v3 = ronda(v0, v1, v2, v3)
    v0, v1, v2, v3 = ronda(v0, v1, v2, v3)
    v0 ^= ultimo
    v2 ^= 0xff
    for _ in range(4):
        v0, v1, v2, v3 = ronda(v0, v1, v2, v3)
    return v0 ^ v1 ^ v2 ^ v3

# vector de prueba del artículo original: clave 00 01 ... 0f y mensaje 00 01 ... 0e
v = siphash24(bytes(range(15)), bytes(range(16)))
print("vector oficial:", hex(v), "  coincide:", v == 0xa129ca6149be45e5)

rng = random.Random(2)
clave_secreta = bytes(rng.randrange(256) for _ in range(16))
base_secreta = rng.randrange(10**6, 2**61 - 1)
funciones = {
    "polinómica sin clave": hash_poli,
    "polinómica, base secreta mod 2^61-1": lambda s: hash_poli(s, base_secreta, 2**61 - 1),
    "SipHash-2-4, clave secreta": lambda s: siphash24(s.encode(), clave_secreta),
}
fabricadas = colisionan(11)
print(f"\n{len(fabricadas)} claves fabricadas contra la función sin clave:")
for nombre, f in funciones.items():
    c, largo = coste(fabricadas, f)
    print(f"  {nombre:38s} comparaciones {c:8d}   cadena más larga {largo:5d}")

Both keyed functions behave as they do on random keys, requiring a few hundred comparisons. Changing only the hash function defeats the attack without changing the table.

Now examine CPython’s boundary. This experiment again targets our own dict and shows a service reviewer what to check: integer hashes are not randomized.

[ ]Integers in CPython are not seededBrowser
import sys, time, random

M = sys.hash_info.modulus                      # 2^61 - 1 en una compilación de 64 bits, 2^31 - 1 en una de 32
print("algoritmo del hash de cadenas:", sys.hash_info.algorithm, "| bits del hash:", sys.hash_info.width, "| módulo de los enteros:", M)
print("hash(7) =", hash(7), "  hash(M) =", hash(M), "  hash(5 * M) =", hash(5 * M))

def tiempo_insertar(claves):
    t0 = time.perf_counter()
    d = {}
    for k in claves:
        d[k] = None
    return time.perf_counter() - t0

print(f"\n{'n':>6} {'enteros normales':>17} {'múltiplos del módulo':>21} {'cociente':>9}")
for n in (500, 1000, 2000, 4000):
    normales = random.Random(n).sample(range(10**9), n)
    t_ok = tiempo_insertar(normales)
    t_mal = tiempo_insertar([i * M for i in range(1, n + 1)])
    print(f"{n:6d} {t_ok * 1000:14.2f} ms {t_mal * 1000:17.2f} ms {t_mal / max(t_ok, 1e-9):9.0f}")

In the browser, Pyodide uses a 32-bit CPython build, so the modulus is 231−12^{31}-1 and the string-hashing algorithm differs, as the code prints. These are build-time choices; the mechanism is identical. Doubling nn multiplies collision-key time by about 44, with some clock noise, while ordinary-key time barely doubles. If integer keys come from outside, the usual remedy is to mix them with a keyed function before using them as dictionary keys, or avoid using them directly.

The professional version

WhatHow in PythonWhat guarantees
Dictionary, setdict, setcompact table, perturbation probing, O(1)\bigO(1) expected; str and bytes with randomized SipHash
Immutable set used as keyfrozensethashable; its hash does not depend on the order
Cryptographic hash (file fingerprints, exact deduplication)hashlib.sha256, hashlib.blake2b(key=...)collision resistance blake2b allows key
Hash seed of stringsvariable PYTHONHASHSEEDrandom (by default) or an integer fixed to reproduce; 0 disable randomization
Contract of __hash__ and __eq__methods of the classa==b⇒hash(a)==hash(b)a == b \Rightarrow \text{hash}(a) == \text{hash}(b); mutable objects should not be hashable

You can observe PYTHONHASHSEED by running several processes. This cannot run in the browser, so the following code is for your computer:

import os, subprocess, sys

for semilla in ("0", "0", "1", "random"):
    env = {**os.environ, "PYTHONHASHSEED": semilla}
    out = subprocess.run([sys.executable, "-c", "print(hash('atlas'))"], env=env, capture_output=True, text=True).stdout.strip()
    print(f"PYTHONHASHSEED={semilla:6s} hash('atlas') = {out}")

The first two lines agree; the third and fourth differ from them. With a fixed seed, or 0 to disable randomization, hashes are reproducible across processes; without it, each process uses its own. This helps reproduce a test failure but is dangerous in production: fixing the seed in an exposed service restores the vulnerability. It also explains why the iteration order of a set of strings changes across runs and must not be treated as deterministic. A dict, by contrast, follows insertion order.

[ ]The hash and eq contract, and how much faster dict isBrowser
# 1) igualdad implica mismo hash; el recíproco no
print("1 == 1.0 == True:", 1 == 1.0 == True, "  hashes:", hash(1), hash(1.0), hash(True))
print("hash(-1), hash(-2):", hash(-1), hash(-2), "  (el -1 está reservado como código de error en C)")

# 2) __eq__ sin __hash__ deja la clase sin hash
class Punto:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __eq__(self, otro):
        return (self.x, self.y) == (otro.x, otro.y)
try:
    {Punto(1, 2): "a"}
except TypeError as e:
    print("sin __hash__:", e)

# 3) una clave mutable que cambia de hash se pierde dentro del diccionario
class PuntoH(Punto):
    __hash__ = lambda self: hash((self.x, self.y))
p = PuntoH(1, 2)
d = {p: "a"}
p.x = 99
print("tras mutar la clave: get(PuntoH(1, 2)) =", d.get(PuntoH(1, 2)), "  get(p) =", d.get(p), "  len(d) =", len(d))

# 4) nuestras tablas frente a dict (escrito en C): lo único fiable es el cociente
import time
rng = random.Random(9)
claves = rng.sample(range(10**9), 4000)
dd = {k: None for k in claves}
tl = Abierta(8192, rng)
tc = Encadenada(rng)
for k in claves:
    tl.insertar(k)
    tc.insertar(k)
def cronometro(f, veces):
    t0 = time.perf_counter()
    for _ in range(veces):
        for k in claves:
            f(k)
    return (time.perf_counter() - t0) / veces
t_dict = cronometro(dd.__contains__, 30)
t_lin = cronometro(lambda k: tl.buscar(k)[0], 3)
t_enc = cronometro(tc.buscar, 3)
print(f"\nmás lentas que dict, por búsqueda: sondeo lineal ×{t_lin / t_dict:.0f}, encadenamiento ×{t_enc / t_dict:.0f}")

In Pyodide, our Python tables are five to ten times slower than dict, which runs in C. Most measured time is interpreter overhead, so only the ratio is reliable. The contract has a practical consequence: dict looks up the hash first, then compares with ==. This is why 1, 1.0, and True represent the same key. The third test illustrates the most common mistake: a mutable key whose hash changes becomes stranded in a cell that is no longer its home. It remains present, contributing to len and appearing during iteration, but lookup cannot reach it through either the mutated object or an object equal to its original value. Consequently del cannot remove it either.

Typical errors

Exercises

ProofThe Carter and Wegman family is universal
Prove: Let pp be a prime and x≠yx \neq y two keys in {0,…,p−1}\{0, \dots, p-1\}. If (a,b)(a, b) is chosen uniformly with a∈{1,…,p−1}a \in \{1, \dots, p-1\} and b∈{0,…,p−1}b \in \{0, \dots, p-1\}, then P[ha,b(x)=ha,b(y)]≤1/m\Pr[h_{a,b}(x) = h_{a,b}(y)] \le 1/m, with ha,b(t)=((at+b) mod p) mod mh_{a,b}(t) = ((at + b) \bmod p) \bmod m.
0
We need to count how many of the p(p−1)p(p-1) parameter pairs make xx and yy collide.

Step 1 of 5. What change of variables simplifies the count?

ProofSpace used by the second level of FKS
Prove: Let hh be a function from a universal family that distributes nn keys into m=nm = n buckets, and let nin_i be the number of keys in bucket ii. Then E[∑ini2]<2n\E\big[\sum_i n_i^2\big] < 2n.
0
It is about expressing ∑ini2\sum_i n_i^2 in terms of the pairs of keys that collide.

Step 1 of 3. How do you rewrite ∑ini2\sum_i n_i^2?

NumericPairs that collide with 32 bits
A hash function of 32 bits (which we will assume is uniform) is applied to n=105n = 10^5 distinct keys. How many key pairs collide in expectation?
NumericProbability of at least one collision
Under the same conditions (n=105n = 10^5 keys and a uniform 32-bit function), what is the probability of there being at least one collision? Use the approximation 1−e−λ1 - e^{-\lambda} with λ\lambda the expected number of pairs.
NumericLinear probing near saturation
A linear probing table with uniform hashing has a load factor α=0.9\alpha = 0.9. How many probes does a failed lookup cost, on average (Knuth's formula)?
NumericCapacity of a dict in CPython
A CPython dict whose index table has m=210=1024m = 2^{10} = 1024 cells is rebuilt when it is filled to 2/32/3. How many elements fit before the rebuild?
QuizWhat fails with a universal family in linear probing
A linear probing table uses a function sampled from a family that is only 2-independent. Which statement is correct?
QuizDefenses against hash flooding
A web service stores in a dictionary the names of the parameters of each request. Which of these measures protect it from a collision flooding attack? (Mark all that apply.)

More than one answer may be correct.

QuizThe 50 % cuckoo threshold
In cuckoo hashing with two tables of rr cells, what explains that insertion starts to fail systematically when the number of keys exceeds rr (total load >50 %> 50\,\%)?
QuizThe hash and eq contract
Which of these statements about __hash__ and __eq__ in Python are true? (Check all that apply.)

More than one answer may be correct.

CodeSimple tabulation hashing
Implement tabulacion(semilla), which returns a hash function h(x) for simple tabulation for 32-bit keys: split x into 4 bytes (the least significant is character 0), use 4 tables of 256 random 32-bit integers generated with random.Random(semilla) (fill table 0 first, then table 1, etc.), and return the XOR of T[i][byte_i]. It should return 32-bit integers and be deterministic for a given seed.
import random

def tabulacion(semilla):
  """Devuelve h(x): XOR de cuatro lecturas en tablas de 256 palabras aleatorias de 32 bits."""
  rng = random.Random(semilla)
  # tu código: crea las 4 tablas y devuelve la función h
  return lambda x: 0
Shift+Enter to run

Summary

Key idea
No fixed hash function is good for every key set. The guarantee therefore comes from drawing the function after the keys have been fixed: a universal family gives constant expected cost, and an unpredictable secret key preserves that behavior in the presence of an adversary.
  • With chaining, expected cost is 1+α/21 + \alpha/2 for successful lookup and α\alpha for unsuccessful lookup, requiring only pairwise collision probability ≤1/m\le 1/m. With open addressing, linear probing’s unsuccessful-lookup cost is 12(1+1/(1−α)2)\frac12(1 + 1/(1-\alpha)^2) because of primary clustering. Robin Hood redistributes displacement and stops unsuccessful lookups earlier. Deletion uses either tombstones, which continue occupying cells, or backward shifting.
  • ha,b(x)=((ax+b) mod p) mod mh_{a,b}(x) = ((ax + b) \bmod p) \bmod m is universal; its proof constructs a bijection between parameters and pairs of values. Universality controls expected collisions, not their dispersion.
  • Each scheme needs its own independence assumptions: universality suffices for chaining and FKS; linear probing needs 5-wise independence, or simple tabulation, which works despite being only 3-wise independent; and cuckoo hashing works reliably below 50% load because its keys form a graph without components containing two cycles.
  • FKS gives worst-case two-access lookup in O(n)\bigO(n) space because E[∑ni2]<2n\E[\sum n_i^2] < 2n. Cuckoo hashing gives worst-case two-access lookup with expected amortized O(1)\bigO(1) insertion.
  • A known unkeyed hash function lets an adversary construct nn colliding keys and drive cost to Θ(n2)\Theta(n^2). The defenses are a PRF with a secret key, such as SipHash, size limits, and trees for long buckets. CPython randomizes str and bytes but not integers.
  • CPython’s dict is a compact open-addressing table with perturbation, rebuilding at 2/32/3 load and preserving insertion order.