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 lives in cell . But the universe of possible keys (strings, 64-bit integers, tuples) is astronomical compared with the number of keys you actually store. A hash function compresses each key to an index in a table of cells, with on the order of . The price is unavoidable: by the pigeonhole principle, if , for any fixed there exist 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 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 buckets, each storing a list of the keys whose equals its index. Insertion adds a key to the list after checking that it is absent; lookup traverses the list for ; deletion removes the key from that list. The quantity governing everything is the load factor
the mean bucket size. With chaining, can exceed : the table does not fill up; its chains simply grow longer.
What must we require of ? 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 , let . The bucket for has length (plus if ), and linearity of expectation together with the collision property gives . This proves (1). For (3), apply the same argument to the pair indicators. For (2), looking up a key compares it with every colliding key preceding it in the list and with itself. Each colliding pair contributes exactly one comparison: the later key is compared with the earlier one. The total number of comparisons over all keys is therefore plus the number of colliding pairs, whose expectation is at most . Dividing by gives .
∎Thus, as long as is proportional to , each operation costs in expectation. To keep bounded, use what you already know about a dynamic array: when exceeds , double the table and reinsert everything with a new function. Each rebuild costs , but occurs only after insertions. Amortized analysis distributes this cost, giving an expected amortized cost of 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 cells, and resolves collisions by looking for another cell. Key follows a probe sequence until it finds a free cell when inserting, or the key itself or an empty cell when searching. With linear probing, : try the next cell, then the next. The probes eventually visit the entire table, and the load must satisfy .
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.
Watch the curves. With chaining, both grow almost linearly in . With linear probing, successful lookup remains reasonable, but unsuccessful lookup grows as : at it costs probes, and at it costs . 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 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 , which grows with . 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 :
Proof
Let be the number of probes. requires the first probes to hit occupied cells. The first does so with probability ; conditional on that, the second does so with probability ; and so on. Each factor is at most , since when . Therefore and .
∎At , uniform probing costs probes and linear probing . 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 beats almost everything else. The crucial point is to keep from approaching .
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 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 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 , where each cell gives the exact collision probability, calculated by enumerating the entire family.
The Carter and Wegman family
The classical family uses a prime (for example, for 60-bit keys) and two random parameters:
Proof
Fix in and consider the pair . Since , with and , we obtain . Here primality of matters: and are coprime, so Bézout’s identity gives an inverse modulo . Conversely, from an ordered pair with we recover the nonzero value and . Thus the map is a bijection between the parameter pairs and the ordered pairs with , using only modular arithmetic.
A collision occurs if and only if . For each fixed , there are at most values satisfying . Consequently at most of the pairs collide, so the probability is at most . Since the count depends on neither nor , it is identical for every pair.
∎Three comments. First, sampling costs two integers: the family contains functions, so choosing one requires about random bits. Second, universal does not mean collision-free: the theorem controls only the expectation. With 2000 keys that are multiples of in 4096 buckets, the number of colliding pairs ranges from to thousands depending on the sampled function, as the code will show. The expectation is close to the bound of pairs, but the range is enormous. Third, the guarantee requires keys to be fixed without information about . 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 keys have any collision is at most by the union bound; and with this probability is less than . 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.
-wise independence implies -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 with coefficients uniform in , the family is -wise independent as functions into . For distinct points , the map from coefficients to the values is a bijection: its matrix is a Vandermonde matrix whose determinant is modulo . The values are therefore uniform and independent. Each evaluation costs multiplications.
How much independence does each algorithm need?
| Scheme | Required guarantee | Reference |
|---|---|---|
| Chaining, expectation of an operation | universality (2 to 2) | Carter and Wegman, 1979 |
| Two-level perfect hashing (FKS) | universality | Fredman, Komlós and Szemerédi, 1984 |
| Linear probing, expected for operation | 5-independence is enough; 4 no | Pagh, Pagh and Ružić, 2007; Pătraşcu and Thorup, 2010 |
| Cuckoo, success with probability | functions -independent in the original analysis | Pagh 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 in expectation, whereas 5-wise independence recovers . 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, , fill four tables with 256 random words each, , and define
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 and 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 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: lookup in the worst case with space. This is perfect hashing. The construction of Fredman, Komlós and Szemerédi (1984) uses only universal hashing:
- First level. A universal function distributes the keys across buckets. Let be the number of keys in bucket .
- Second level. Bucket gets its own table of size and its own universal function , repeatedly sampled until there are no collisions.
To look up , compute and inspect cell of table : 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 gives , where counts the key pairs colliding at the first level. Linearity of expectation and universality give , hence . For the second claim, the expected number of collisions among keys in a table of cells is at most . By Markov’s inequality, the probability of any collision is less than .
∎Applying Markov again gives . Simply retry the first level until , 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 , expected space at most cells plus the function parameters, and two-access lookup. Below, you will construct it and measure , which comes out very close to .
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, and , each with cells, and two functions . The invariant is that every key occupies either or . Lookup checks exactly these two cells, giving two accesses in the worst case. Inserting places it in . If that cell is occupied, evict its resident to its other cell , 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 , abandon the attempt: draw two new functions and reinsert all keys.
The drawing also shows the graph that explains the mechanism. Its vertices are the cells, and each key is an edge between and . Placing keys means orienting each edge toward its occupied cell, so that every cell receives at most one edge. In a connected component with vertices and edges, this is possible only if : 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 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 vertices and edges. In the Erdős-Rényi model with edges on vertices, is the phase-transition threshold. Below it, components are small: trees and occasional isolated cycles, with probability of a component containing two cycles. Above it, a giant component appears with many cycles. Here , so the threshold is , 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 functions the threshold rises to , and with to , 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 -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 keys with the same hash and sends them. All reach the same bucket; each insertion traverses a longer chain, and total cost becomes instead of . 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, . Its known weakness is sufficient: the strings ‘Aa’ and ‘BB’ share a hash, . Because the hash is polynomial, concatenating equal-length blocks of these strings preserves equality. With blocks, this produces distinct strings with exactly the same 32-bit hash. The figure compares three functions on ordinary and constructed keys.
Defenses
- 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 under a random function. For strings, a guaranteed variant uses a polynomial hash modulo a prime with a random secret base. Two distinct strings of length at most collide with probability at most when the base is uniform in , because their difference is a nonzero polynomial in the base of degree less than , with at most roots. Nonzero here requires either that no character has value or that length enters the hash; otherwise
"a"and"\x00a"yield the same polynomial. With and 100-character strings, the bound is less than . - 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
strandbytes. - Bound the work. Limiting the number of request parameters or the body size keeps small. This was the quickest mitigation after the December 2011 disclosure: PHP 5.3.9 introduced
max_input_varsin January 2012. Converting long buckets into balanced trees also limits a chain’s cost to . Java 8’sHashMapdoes this for buckets with more than 8 entries, provided keys are comparable. The next lesson on ordered structures explains how. - Detect. With 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 , so that integer and all its multiples have hash . 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 small cells, occupying 1, 2, 4 or 8 bytes depending on . 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 adictremembers order and iteration traverses a contiguous array without jumps.
The probe sequence is not linear. It starts at and advances using , where 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 is a congruential generator of full period by the Hull-Dobell theorem: the increment is odd and the multiplier is . It therefore eventually visits every cell, even after perturbation runs out. Perturbation gradually introduces high hash bits that 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 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:
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 , 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.
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 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:
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.
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 it costs about probes rather than linear probing’s . Knuth’s formula is asymptotic, ; here we use eight 2048-cell tables per point. Agreement is excellent at , differs by 12% at ( versus ), and at theory gives , well above the measured . This is not an error: two effects combine. First, finite size. Knuth also gives the exact formula for cells and keys, . With and it gives , rather than ; at it gives . Convergence to the limit is slow as approaches . 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 the exact expectation is , and at it is , rather than the limiting and . The measured red curve lies below the theoretical curve. Next comes cuckoo hashing.
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 . Each rebuild is a Las Vegas retry. With 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 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 is close to .
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.
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 exactly: doubling 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.
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.
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 and the string-hashing algorithm differs, as the code prints. These are build-time choices; the mechanism is identical. Doubling multiplies collision-key time by about , 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
| What | How in Python | What guarantees |
|---|---|---|
| Dictionary, set | dict, set | compact table, perturbation probing, expected; str and bytes with randomized SipHash |
| Immutable set used as key | frozenset | hashable; 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 strings | variable PYTHONHASHSEED | random (by default) or an integer fixed to reproduce; 0 disable randomization |
Contract of __hash__ and __eq__ | methods of the class | ; 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.
# 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
Step 1 of 5. What change of variables simplifies the count?
Step 1 of 3. How do you rewrite ?
dict whose index table has cells is rebuilt when it is filled to . How many elements fit before the rebuild?More than one answer may be correct.
__hash__ and __eq__ in Python are true? (Check all that apply.)More than one answer may be correct.
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: 0Summary
- With chaining, expected cost is for successful lookup and for unsuccessful lookup, requiring only pairwise collision probability . With open addressing, linear probing’s unsuccessful-lookup cost is because of primary clustering. Robin Hood redistributes displacement and stops unsuccessful lookups earlier. Deletion uses either tombstones, which continue occupying cells, or backward shifting.
- 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 space because . Cuckoo hashing gives worst-case two-access lookup with expected amortized insertion.
- A known unkeyed hash function lets an adversary construct colliding keys and drive cost to . The defenses are a PRF with a secret key, such as SipHash, size limits, and trees for long buckets. CPython randomizes
strandbytesbut not integers. - CPython’s
dictis a compact open-addressing table with perturbation, rebuilding at load and preserving insertion order.