TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Universal and k-Wise Independent Hash Families

Universal and k-Wise Independent Hash Families

Analyses of hashing usually begin "assume hh is a truly random function". A truly random function on a universe of size uu needs ulg⁡mu \lg m 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. kk-wise independent families provide exactly that much randomness with a description of only kk 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 H\mathcal{H} be a family of functions U→[m]={0,…,m−1}U \to [m] = \{0, \ldots, m-1\} and hh uniform from H\mathcal{H}.

Property Definition Typical use
universal Pr⁡[h(x)=h(y)]≤1m\Pr[h(x) = h(y)] \le \frac1m for all x≠yx \ne y chaining: expected chain length 1+α1 + \alpha
kk-wise independent for all distinct x1,…,xkx_1, \ldots, x_k and all y1,…,yk∈[m]y_1, \ldots, y_k \in [m]: Pr⁡[h(xi)=yi for all i]=m−k\Pr[h(x_i) = y_i \text{ for all } i] = m^{-k} moments up to order kk behave as for a random function

2-wise independence is also called strong universality (Wegman and Carter, 1981); it implies universality, since Pr⁡[h(x)=h(y)]=∑aPr⁡[h(x)=a,h(y)=a]=m⋅m−2\Pr[h(x) = h(y)] = \sum_a \Pr[h(x) = a, h(y) = a] = m \cdot m^{-2}. Each level implies the ones below: a kk-wise independent family is jj-wise independent for every j≤kj \le k.

Random polynomials

Let pp be a prime and identify the universe with Zp\mathbb{Z}_p. For k≥1k \ge 1, choose coefficients a0,…,ak−1a_0, \ldots, a_{k-1} independently and uniformly from Zp\mathbb{Z}_p and set

h(x)=(ak−1xk−1+⋯+a1x+a0) mod p.h(x) = \bigl(a_{k-1}x^{k-1} + \cdots + a_1 x + a_0\bigr) \bmod p .

Theorem (Wegman and Carter, 1981). This family of pkp^k functions Zp→Zp\mathbb{Z}_p \to \mathbb{Z}_p is kk-wise independent.

Proof. Fix distinct x1,…,xkx_1, \ldots, x_k and arbitrary targets y1,…,yky_1, \ldots, y_k. Over the field Zp\mathbb{Z}_p there is exactly one polynomial of degree less than kk through the kk points (xi,yi)(x_i, y_i) (Lagrange interpolation; equivalently, the Vandermonde matrix of distinct xix_i is invertible). So exactly one of the pkp^k coefficient vectors works, with probability p−kp^{-k}. □\square

The family is not (k+1)(k+1)-wise independent: kk values determine the polynomial, hence every other value. The description costs klg⁡pk \lg p bits and an evaluation costs kk multiplications by Horner's rule, so higher independence is paid for linearly.

To hash into m<pm < p buckets, use h(x) mod mh(x) \bmod m. The result is no longer exactly uniform: each bucket has probability between ⌊p/m⌋/p\lfloor p/m \rfloor / p and ⌈p/m⌉/p\lceil p/m \rceil / p, so with p≫mp \gg m the family is kk-wise independent up to a factor (1+m/p)k(1 + m/p)^k, which analyses absorb easily.

The program verifies the theorem exhaustively for p=7p = 7: for each kk it enumerates all 7k7^k polynomials and checks that every kk-tuple of distinct keys is mapped uniformly onto Z7k\mathbb{Z}_7^k, then shows that k+1k + 1 keys are not.

python · try it yourself
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 bb and a set of nn keys, and let XX be the number of keys hashed to bb. XjX^j expands into sums over jj-tuples of keys, so E[Xj]\mathbb{E}[X^j] depends only on the joint distribution of at most jj hash values at a time. Hence for a kk-wise independent family, the first kk moments of every bucket count are exactly those of the binomial distribution, as if hh were truly random. Chebyshev's inequality uses the second moment, so 2-wise independence suffices for it; a bound via the fourth moment, Pr⁡[∣X−μ∣≥t]≤E[(X−μ)4]/t4\Pr[\lvert X - \mu \rvert \ge t] \le \mathbb{E}[(X - \mu)^4]/t^4, needs 4-wise independence.

The program computes the exact moments E[Xj]\mathbb{E}[X^j] of the count in bucket 0 for 10 keys in Z11\mathbb{Z}_{11}, averaging over all functions in each family, and compares them with the binomial values.

python · try it yourself
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 kk-wise family matches the binomial in moments 1,…,k1, \ldots, k 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, nn keys, m=Θ(n)m = \Theta(n) buckets):

  • Chaining: universality gives expected O(1)O(1) per operation. The longest chain is O(n)O(\sqrt n) with 2-wise independence (from the second moment), and Θ(log⁡n/log⁡log⁡n)\Theta(\log n / \log\log n), as for a random function, with Θ(log⁡n/log⁡log⁡n)\Theta(\log n / \log\log n)-wise independence.
  • Linear probing: 5-wise independence gives O(1)O(1) 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, ha(x)=(ax mod 2w)≫(w−ℓ)h_a(x) = (a x \bmod 2^w) \gg (w - \ell) for a random odd ww-bit aa, has collision probability at most 2/2ℓ2/2^\ell (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 kk-wise independent family modulo p=261−1p = 2^{61} - 1 with Horner evaluation and 128-bit products, used for a chained table of n=100 000n = 100\,000 consecutive integer keys in m=nm = n 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 (1+n−1m≈21 + \frac{n-1}{m} \approx 2 per key).

cpp · try it yourself
#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 pp, 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 kk over Zp\mathbb{Z}_p exactly kk-wise independent?

  1. Because pp is large
  2. Because exactly one polynomial of degree less than kk passes through any kk points with distinct xx-coordinates
  3. Because the coefficients are distinct
  4. Because polynomials are injective

Which is the weakest property that makes the variance of a bucket count equal to the fully random case?

  1. Universality
  2. 2-wise independence
  3. 4-wise independence
  4. Full independence

How many random coefficients describe a function from the kk-wise independent polynomial family?

  1. 1
  2. kk
  3. k2k^2
  4. pp

What level of independence is known to suffice for linear probing to take expected constant time per operation?

  1. 2-wise
  2. 3-wise
  3. 5-wise
  4. log⁡n\log n-wise only