TExcelTAD

Universal Hashing

Every fixed hash function has a bad set of keys: some slot is the hash value of at least ∣U∣/m\lvert U \rvert / m 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 H\mathcal{H} of functions U→{0,…,m−1}U \to \{0, \ldots, m - 1\} is universal if for every pair of distinct keys k≠ℓk \ne \ell,

∣{h∈H:h(k)=h(ℓ)}∣≤∣H∣m\bigl\lvert \{ h \in \mathcal{H} : h(k) = h(\ell) \} \bigr\rvert \le \frac{\lvert \mathcal{H} \rvert}{m}

In words: if hh is drawn uniformly from H\mathcal{H}, any two fixed keys collide with probability at most 1/m1/m, exactly as if h(k)h(k) and h(ℓ)h(\ell) 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 hh be chosen uniformly from a universal family, and let a chained table hold a fixed set of nn keys, so α=n/m\alpha = n/m. For any key kk, the expected length of the chain h(k)h(k) is at most α\alpha if kk is not stored, and at most 1+α1 + \alpha if it is.

Proof. For each stored key ℓ≠k\ell \ne k let XℓX_\ell be the indicator of h(k)=h(ℓ)h(k) = h(\ell). By universality E[Xℓ]=Pr⁡[h(k)=h(ℓ)]≤1/mE[X_\ell] = \Pr[h(k) = h(\ell)] \le 1/m. The chain of kk holds the stored keys colliding with kk, plus kk itself if it is stored. If kk is not stored there are nn keys ℓ\ell, so the expected length is ∑ℓE[Xℓ]≤n/m=α\sum_\ell E[X_\ell] \le n/m = \alpha. If it is stored there are n−1n - 1 others, so the expectation is at most 1+(n−1)/m<1+α1 + (n-1)/m < 1 + \alpha.

The expectation is over the random choice of hh only; the keys can be anything, even chosen by an adversary, as long as they are fixed before hh is drawn (or the adversary cannot observe hh). Corollary: with m=Θ(n)m = \Theta(n), any sequence of ss INSERT, SEARCH and DELETE operations containing O(m)O(m) inserts takes Θ(s)\Theta(s) expected time.

A universal family

Choose a prime pp larger than every key, so keys are in {0,…,p−1}\{0, \ldots, p - 1\}, and any m<pm < p. For a∈{1,…,p−1}a \in \{1, \ldots, p - 1\} and b∈{0,…,p−1}b \in \{0, \ldots, p - 1\} let

hab(k)=((ak+b) mod p) mod mh_{ab}(k) = \bigl( (ak + b) \bmod p \bigr) \bmod m

The family Hpm={hab}\mathcal{H}_{pm} = \{ h_{ab} \} has p(p−1)p(p - 1) functions, and drawing one means drawing aa and bb.

Proof that the family is universal (sketch)

Fix keys k≠ℓk \ne \ell and write r=(ak+b) mod pr = (ak + b) \bmod p, s=(aℓ+b) mod ps = (a\ell + b) \bmod p.

  1. No collisions modulo pp. r−s≡a(k−ℓ)(modp)r - s \equiv a(k - \ell) \pmod p. Both aa and k−ℓk - \ell are nonzero modulo the prime pp, so their product is nonzero: r≠sr \ne s.
  2. Every pair (r,s)(r, s) with r≠sr \ne s comes from exactly one (a,b)(a, b). Given rr and ss, solve: a=(r−s)(k−ℓ)−1 mod pa = (r - s)(k - \ell)^{-1} \bmod p (the inverse exists because pp is prime) and b=(r−ak) mod pb = (r - ak) \bmod p. So the map (a,b)↦(r,s)(a, b) \mapsto (r, s) is a bijection between the p(p−1)p(p-1) functions and the p(p−1)p(p-1) ordered pairs of distinct residues. A random habh_{ab} therefore gives a uniformly random pair r≠sr \ne s.
  3. Collisions come only from the final mod mm. For a fixed rr, the values s≠rs \ne r in {0,…,p−1}\{0, \ldots, p-1\} with s≡r(modm)s \equiv r \pmod m number at most ⌈p/m⌉−1≤(p−1)/m\lceil p/m \rceil - 1 \le (p - 1)/m. Since ss is uniform over the p−1p - 1 values other than rr, the collision probability is at most (p−1)/mp−1=1m\frac{(p-1)/m}{p-1} = \frac{1}{m}.

The definition can be checked exhaustively for small parameters. With p=17p = 17 and m=5m = 5 the family has 17⋅16=27217 \cdot 16 = 272 functions, and universality allows at most 272/5=54.4272/5 = 54.4 of them, so 54, to make any pair collide.

python · try it yourself
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 42/272≈0.15442/272 \approx 0.154, below 1/m=0.21/m = 0.2. The family is a little better than the definition requires.

Beating the adversary

The keys 0,m,2m,…0, m, 2m, \ldots 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 h(k)=k mod mh(k) = k \bmod m and then with five random draws of habh_{ab}, using the Mersenne prime p=231−1p = 2^{31} - 1.

python · try it yourself
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 11 plus the expected number of colliding pairs divided by nn, at most 1+(n2)1m⋅1n=1+n−12m<1.51 + \binom{n}{2} \frac{1}{m} \cdot \frac{1}{n} = 1 + \frac{n-1}{2m} < 1.5 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 pp, which some draws spread better than others), and every one of them is far from the 500 of the fixed function.

In C++

With p=231−1p = 2^{31} - 1, the product akak fits in 64 bits, so habh_{ab} 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.

cpp · try it yourself
#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  mod p\bmod p family needs a division per hash. A faster family for ww-bit keys and m=2pm = 2^p slots is multiply-shift: draw a random odd ww-bit aa and let ha(k)=(ak mod 2w)≫(w−p)h_a(k) = (a k \bmod 2^w) \gg (w - p). It is not quite universal, but any two keys collide with probability at most 2/m2/m, 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 kk-wise independence) are needed for some algorithms, such as linear probing: 5-wise independent hashing is enough for its expected O(1)O(1) 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 str hash is SipHash with a random key (set PYTHONHASHSEED to fix it), and Rust's HashMap seeds 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 H\mathcal{H} of 600 functions into m=10m = 10 slots is universal. At most how many of its functions can map two given distinct keys to the same slot?

  1. 6
  2. 10
  3. 60
  4. 600

In the proof that habh_{ab} is universal, why can k≠ℓk \ne \ell never collide modulo pp?

  1. Because bb cancels and a(k−ℓ)a(k - \ell) is a product of two nonzero numbers modulo a prime
  2. Because m<pm < p
  3. Because aa is odd
  4. They can; the final mod mm removes the collisions

Universal hashing guarantees expected O(1+α)O(1 + \alpha) search cost...

  1. for random keys only
  2. for every fixed set of keys, averaged over the random choice of hh
  3. in the worst case
  4. only when mm is a power of 2