Universal and k-Wise Independent Hash Families
Analyses of hashing usually begin "assume is a truly random function". A truly random function on a universe of size needs random bits to describe, far too many to store. What saves hashing is that most analyses only look at a few keys at a time: chaining needs only pairs to behave randomly, Chebyshev-type load bounds need pairs, linear probing needs five keys at a time. -wise independent families provide exactly that much randomness with a description of only numbers. This lesson defines the hierarchy, builds the families from random polynomials, and measures what each level buys. The first level, universal hashing for chaining, is covered in Universal Hashing.
The hierarchy
Let be a family of functions and uniform from .
| Property | Definition | Typical use |
|---|---|---|
| universal | for all | chaining: expected chain length |
| -wise independent | for all distinct and all : | moments up to order behave as for a random function |
2-wise independence is also called strong universality (Wegman and Carter, 1981); it implies universality, since . Each level implies the ones below: a -wise independent family is -wise independent for every .
Random polynomials
Let be a prime and identify the universe with . For , choose coefficients independently and uniformly from and set
Theorem (Wegman and Carter, 1981). This family of functions is -wise independent.
Proof. Fix distinct and arbitrary targets . Over the field there is exactly one polynomial of degree less than through the points (Lagrange interpolation; equivalently, the Vandermonde matrix of distinct is invertible). So exactly one of the coefficient vectors works, with probability .
The family is not -wise independent: values determine the polynomial, hence every other value. The description costs bits and an evaluation costs multiplications by Horner's rule, so higher independence is paid for linearly.
To hash into buckets, use . The result is no longer exactly uniform: each bucket has probability between and , so with the family is -wise independent up to a factor , which analyses absorb easily.
The program verifies the theorem exhaustively for : for each it enumerates all polynomials and checks that every -tuple of distinct keys is mapped uniformly onto , then shows that keys are not.
from itertools import combinations, product
from collections import Counter
p = 7
def h(coeffs, x):
v = 0
for a in reversed(coeffs): # Horner: a_{k-1} first
v = (v * x + a) % p
return v
for k in [1, 2, 3]:
family = list(product(range(p), repeat=k))
ok_k = all(
len(set(Counter(tuple(h(c, x) for x in xs) for c in family).values())) == 1
and len(Counter(tuple(h(c, x) for x in xs) for c in family)) == p ** k
for xs in combinations(range(p), k))
xs = tuple(range(k + 1))
seen = len(Counter(tuple(h(c, x) for x in xs) for c in family))
print(f"k = {k}: {len(family):3} functions; every {k}-tuple uniform: {ok_k}; "
f"values on {k + 1} keys take only {seen} of {p ** (k + 1)} possible tuples")k = 1: 7 functions; every 1-tuple uniform: True; values on 2 keys take only 7 of 49 possible tuples
k = 2: 49 functions; every 2-tuple uniform: True; values on 3 keys take only 49 of 343 possible tuples
k = 3: 343 functions; every 3-tuple uniform: True; values on 4 keys take only 343 of 2401 possible tuples
What independence buys: matching moments
Fix a bucket and a set of keys, and let be the number of keys hashed to . expands into sums over -tuples of keys, so depends only on the joint distribution of at most hash values at a time. Hence for a -wise independent family, the first moments of every bucket count are exactly those of the binomial distribution, as if were truly random. Chebyshev's inequality uses the second moment, so 2-wise independence suffices for it; a bound via the fourth moment, , needs 4-wise independence.
The program computes the exact moments of the count in bucket 0 for 10 keys in , averaging over all functions in each family, and compares them with the binomial values.
from fractions import Fraction
from itertools import product
from math import comb
p, keys = 11, range(10)
def binomial_moment(n, q, j):
return sum(Fraction(comb(n, x)) * q ** x * (1 - q) ** (n - x) * x ** j for x in range(n + 1))
q = Fraction(1, p)
print("moment j: 1 2 3 4")
print("binomial " + " ".join(f"{float(binomial_moment(10, q, j)):8.4f}" for j in range(1, 5)))
for k in [1, 2, 3, 4]:
moments = [Fraction(0)] * 5
for coeffs in product(range(p), repeat=k):
x = 0
for key in keys:
v = 0
for a in reversed(coeffs):
v = (v * key + a) % p
x += v == 0
for j in range(1, 5):
moments[j] += x ** j
total = p ** k
print(f"{k}-wise " + " ".join(f"{float(moments[j] / total):8.4f}" for j in range(1, 5)))moment j: 1 2 3 4
binomial 0.9091 1.6529 3.6814 9.7056
1-wise 0.9091 9.0909 90.9091 909.0909
2-wise 0.9091 1.6529 9.0909 83.4711
3-wise 0.9091 1.6529 3.6814 13.1480
4-wise 0.9091 1.6529 3.6814 9.7056
The -wise family matches the binomial in moments and (in general) not beyond: the 1-wise family (random constants) puts all keys in the same bucket, so its higher moments are huge.
How much independence is enough?
Results for common tasks, stated (keys are arbitrary, keys, buckets):
- Chaining: universality gives expected per operation. The longest chain is with 2-wise independence (from the second moment), and , as for a random function, with -wise independence.
- Linear probing: 5-wise independence gives expected time per operation (Pagh, Pagh and Ružić, 2007), and there are 4-wise independent families for which it does not (Pătraşcu and Thorup, 2010).
- Fast practical families: multiply-shift, for a random odd -bit , has collision probability at most (Dietzfelbinger, Hagerup, Katajainen and Penttonen, 1997) with one multiplication and one shift. Simple tabulation, which XORs random table entries indexed by the bytes of the key, is only 3-wise independent but provably behaves like a random function for linear probing, cuckoo hashing and min-wise hashing (Pătraşcu and Thorup, 2012).
In C++
A -wise independent family modulo with Horner evaluation and 128-bit products, used for a chained table of consecutive integer keys in buckets. The coefficients come from a fixed-seed std::mt19937_64. The table reports the longest chain and the average squared chain length, whose expectation is the same for every 2-wise independent family ( per key).
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
using u64 = std::uint64_t;
const u64 P = (1ULL << 61) - 1;
struct PolyHash {
std::vector<u64> a; // a[0] .. a[k-1]
PolyHash(int k, std::mt19937_64& rng) : a(k) { for (auto& c : a) c = rng() % P; }
u64 operator()(u64 x) const {
unsigned __int128 v = 0;
for (size_t i = a.size(); i-- > 0;) v = (v * x + a[i]) % P;
return (u64)v;
}
};
int main() {
std::mt19937_64 rng(90);
const int n = 100000, m = n;
std::printf(" k longest chain mean chain length seen by a key\n");
for (int k : {2, 3, 5}) {
PolyHash h(k, rng);
std::vector<int> load(m, 0);
for (u64 x = 0; x < (u64)n; ++x) load[h(x) % m]++;
double sq = 0;
for (int c : load) sq += double(c) * c;
std::printf("%2d %13d %31.3f\n", k, *std::max_element(load.begin(), load.end()), sq / n);
}
} k longest chain mean chain length seen by a key
2 2 1.511
3 8 1.994
5 8 1.996
The 3-wise and 5-wise functions behave like a random function: mean chain length near 2, longest chain 8. The linear (2-wise) function is too regular on consecutive keys: it maps an arithmetic progression of keys to an arithmetic progression modulo , which spreads them almost evenly over the buckets. That is good luck here, but the same regularity is what makes linear functions fail on other structured key sets, for example with linear probing. The guarantees differ in what they promise for every key set, not in typical behaviour on one input.
Test yourself
Why is the family of random polynomials of degree less than over exactly -wise independent?
- Because is large
- Because exactly one polynomial of degree less than passes through any points with distinct -coordinates
- Because the coefficients are distinct
- Because polynomials are injective
Which is the weakest property that makes the variance of a bucket count equal to the fully random case?
- Universality
- 2-wise independence
- 4-wise independence
- Full independence
How many random coefficients describe a function from the -wise independent polynomial family?
- 1
What level of independence is known to suffice for linear probing to take expected constant time per operation?
- 2-wise
- 3-wise
- 5-wise
- -wise only