Universal Hashing
Every fixed hash function has a bad set of keys: some slot is the hash value of at least keys, and an adversary who knows the function can store exactly those (Chaining under Simple Uniform Hashing). The fix is the same as for quicksort's bad inputs: randomize the algorithm, not the input. When the table is created, it picks its hash function at random from a carefully designed family. No input is then bad for more than a few of the functions, and the expected cost is small for every set of keys.
The definition
A finite family of functions is universal if for every pair of distinct keys ,
In words: if is drawn uniformly from , any two fixed keys collide with probability at most , exactly as if and were independent random slots. Universality asks only about pairs; that turns out to be all the chaining analysis needs.
Universality gives short chains for every input
Theorem. Let be chosen uniformly from a universal family, and let a chained table hold a fixed set of keys, so . For any key , the expected length of the chain is at most if is not stored, and at most if it is.
Proof. For each stored key let be the indicator of . By universality . The chain of holds the stored keys colliding with , plus itself if it is stored. If is not stored there are keys , so the expected length is . If it is stored there are others, so the expectation is at most .
The expectation is over the random choice of only; the keys can be anything, even chosen by an adversary, as long as they are fixed before is drawn (or the adversary cannot observe ). Corollary: with , any sequence of INSERT, SEARCH and DELETE operations containing inserts takes expected time.
A universal family
Choose a prime larger than every key, so keys are in , and any . For and let
The family has functions, and drawing one means drawing and .
Proof that the family is universal (sketch)
Fix keys and write , .
- No collisions modulo . . Both and are nonzero modulo the prime , so their product is nonzero: .
- Every pair with comes from exactly one . Given and , solve: (the inverse exists because is prime) and . So the map is a bijection between the functions and the ordered pairs of distinct residues. A random therefore gives a uniformly random pair .
- Collisions come only from the final mod . For a fixed , the values in with number at most . Since is uniform over the values other than , the collision probability is at most .
The definition can be checked exhaustively for small parameters. With and the family has functions, and universality allows at most of them, so 54, to make any pair collide.
from itertools import combinations
p, m = 17, 5
family = [(a, b) for a in range(1, p) for b in range(p)]
def h(a, b, k):
return ((a * k + b) % p) % m
worst, worst_pair, total = 0, None, 0
for k, l in combinations(range(p), 2):
c = sum(h(a, b, k) == h(a, b, l) for a, b in family)
total += c
if c > worst:
worst, worst_pair = c, (k, l)
pairs = p * (p - 1) // 2
print(f"{len(family)} functions, {pairs} key pairs")
print(f"most functions making one pair collide: {worst} (pair {worst_pair}); bound |H|/m = {len(family) / m}")
print(f"average collision probability over pairs: {total / (pairs * len(family)):.4f}, 1/m = {1 / m}")272 functions, 136 key pairs
most functions making one pair collide: 42 (pair (0, 1)); bound |H|/m = 54.4
average collision probability over pairs: 0.1544, 1/m = 0.2
Every pair collides under at most 42 of the 272 functions, a probability of , below . The family is a little better than the definition requires.
Beating the adversary
The keys that destroyed the division method (Chaining under Simple Uniform Hashing) are harmless against a random member of the family. The program builds a table of 1000 slots for 1000 such keys, first with and then with five random draws of , using the Mersenne prime .
import random
p, m, n = 2 ** 31 - 1, 1000, 1000
keys = [i * m for i in range(n)] # the adversary's keys
def chain_stats(h):
lengths = [0] * m
for k in keys:
lengths[h(k)] += 1
searches = sum(L * (L + 1) // 2 for L in lengths) / n # average successful search
return max(lengths), searches
print("k mod m: longest chain %4d, average successful search %6.2f" % chain_stats(lambda k: k % m))
rng = random.Random(2024)
for draw in range(5):
a, b = rng.randrange(1, p), rng.randrange(p)
longest, cost = chain_stats(lambda k: ((a * k + b) % p) % m)
print(f"random h_ab #{draw + 1}: longest chain {longest:4}, average successful search {cost:6.2f}")
print("expected value is at most 1 + (n - 1)/(2m) =", 1 + (n - 1) / (2 * m))k mod m: longest chain 1000, average successful search 500.50
random h_ab #1: longest chain 2, average successful search 1.34
random h_ab #2: longest chain 4, average successful search 1.96
random h_ab #3: longest chain 2, average successful search 1.10
random h_ab #4: longest chain 2, average successful search 1.32
random h_ab #5: longest chain 3, average successful search 1.35
expected value is at most 1 + (n - 1)/(2m) = 1.4995
The average successful search counts, for each key, its position in its chain. Its expectation is plus the expected number of colliding pairs divided by , at most by universality. Single draws scatter around that value (here from 1.10 to 1.96, because keys in an arithmetic progression map to an arithmetic progression modulo , which some draws spread better than others), and every one of them is far from the 500 of the fixed function.
In C++
With , the product fits in 64 bits, so is a few integer operations. The program draws a function with std::mt19937_64 and a fixed seed, then hashes the adversary's keys into a table.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
struct UniversalHash {
static constexpr std::uint64_t P = 2147483647; // 2^31 - 1, a prime
std::uint64_t a, b, m;
UniversalHash(std::uint64_t m_, std::mt19937_64& rng)
: a(1 + rng() % (P - 1)), b(rng() % P), m(m_) {}
std::uint64_t operator()(std::uint64_t k) const { return ((a * k + b) % P) % m; }
};
int main() {
const std::uint64_t m = 1000, n = 1000;
std::mt19937_64 rng(2024);
for (int draw = 1; draw <= 3; ++draw) {
UniversalHash h(m, rng);
std::vector<int> len(m);
for (std::uint64_t i = 0; i < n; ++i) ++len[h(i * m)]; // keys 0, m, 2m, ...
long work = 0;
for (int L : len) work += static_cast<long>(L) * (L + 1) / 2;
std::printf("draw %d: a = %llu, b = %llu, longest chain %d, average successful search %.2f\n",
draw, static_cast<unsigned long long>(h.a), static_cast<unsigned long long>(h.b),
*std::max_element(len.begin(), len.end()), double(work) / n);
}
}draw 1: a = 524887571, b = 298574265, longest chain 2, average successful search 1.09
draw 2: a = 1103417376, b = 130125474, longest chain 2, average successful search 1.15
draw 3: a = 1909951157, b = 73300109, longest chain 3, average successful search 1.60
In practice
- The family needs a division per hash. A faster family for -bit keys and slots is multiply-shift: draw a random odd -bit and let . It is not quite universal, but any two keys collide with probability at most , which is just as good for the analysis up to the constant. It is the multiplication method with a random multiplier.
- Universality bounds expected chain lengths, not the longest chain. Stronger properties (pairwise or -wise independence) are needed for some algorithms, such as linear probing: 5-wise independent hashing is enough for its expected cost, while some families with only 4-wise independence are not.
- Languages exposed to untrusted input seed their hash functions at start-up: Python's
strhash is SipHash with a random key (setPYTHONHASHSEEDto fix it), and Rust'sHashMapseeds its hasher with random keys by default. This defends against hash-flooding attacks, in which an attacker sends many colliding keys to slow a server down.
Test yourself
A family of 600 functions into slots is universal. At most how many of its functions can map two given distinct keys to the same slot?
- 6
- 10
- 60
- 600
In the proof that is universal, why can never collide modulo ?
- Because cancels and is a product of two nonzero numbers modulo a prime
- Because
- Because is odd
- They can; the final mod removes the collisions
Universal hashing guarantees expected search cost...
- for random keys only
- for every fixed set of keys, averaged over the random choice of
- in the worst case
- only when is a power of 2