Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

k-Independence & Tabulation Hashing

How much randomness a hash function really needs.

A truly random function from 64-bit keys to slots would need a table with 2642^{64} entries. Real hash tables run on functions described by a few random words, so the real question is how much randomness each application needs. Pairwise independence is enough for chaining, linear probing needs exactly five-wise, and a trick from 1970 computer chess, a few tables of random numbers combined by XOR, behaves like full randomness almost everywhere.

What you’ll learn

  • Define kk-independence and prove that random polynomials of degree k−1k-1 over a prime field are kk-independent.
  • Prove what limited independence buys for chaining: a maximum load of O(n)O(\sqrt n) from pairwise independence and O(log⁡n/log⁡log⁡n)O(\log n/\log\log n) from Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n)-independence.
  • State the independence thresholds for linear probing (5 suffices, 4 does not) and explain why fast weak families fail on structured keys.
  • Prove that simple tabulation is 3-independent but not 4-independent, and state what Pătraşcu and Thorup proved it achieves anyway.

Independence as a resource

A fully random function is ∣U∣\abs U-independent, but storing one takes ∣U∣log⁡2m\abs U \log_2 m bits, as large as a table indexed by every possible key. The art is to get the guarantee an application needs from a short random seed and a fast evaluation. kk-independence is the standard yardstick, and the classic construction is a random polynomial.

DerivationProof
  1. (1x1⋯x1k−1⋮⋮⋮1xk⋯xkk−1)(a0⋮ak−1)=(y1⋮yk)\begin{pmatrix} 1 & x_1 & \cdots & x_1^{k-1} \\ \vdots & \vdots & & \vdots \\ 1 & x_k & \cdots & x_k^{k-1} \end{pmatrix} \begin{pmatrix} a_0 \\ \vdots \\ a_{k-1} \end{pmatrix} = \begin{pmatrix} y_1 \\ \vdots \\ y_k \end{pmatrix}

    Fix distinct keys x1,…,xkx_1, \dots, x_k and targets y1,…,yk∈Zpy_1, \dots, y_k \in \Z_p. The coefficients that hit every target solve a Vandermonde system:

  2. Pr⁡[q(x1)=y1,…,q(xk)=yk]=p−k\Pr\big[q(x_1) = y_1, \dots, q(x_k) = y_k\big] = p^{-k}

    Its determinant ∏i<j(xj−xi)\prod_{i<j}(x_j - x_i) is nonzero modulo the prime pp, so exactly one coefficient vector works: Lagrange interpolation over a field. Out of pkp^k equally likely vectors,

  3. (1−m/pm)k≤Pr⁡[h(x1)=s1,…,h(xk)=sk]≤(1+m/pm)k\left(\frac{1 - m/p}{m}\right)^{k} \le \Pr\big[h(x_1) = s_1, \dots, h(x_k) = s_k\big] \le \left(\frac{1 + m/p}{m}\right)^{k}

    Reducing modulo mm sends ⌊p/m⌋\lfloor p/m \rfloor or ⌈p/m⌉\lceil p/m \rceil residues to each slot, so each slot's probability lies within a factor 1±m/p1 \pm m/p of 1/m1/m, independently for the kk keys:

python
import random

P = (1 << 61) - 1                          # Mersenne prime

def make_k_independent(k, m):
    coeffs = [random.randrange(P) for _ in range(k)]   # the seed: k words
    def h(x):                              # integer key, 0 <= x < P
        v = 0
        for c in coeffs:                   # Horner's rule: k multiplications
            v = (v * x + c) % P
        return v % m
    return h

Seed of kk words, kk multiplications per key. With p=261−1p = 2^{61} - 1 the factor (1±m/p)k(1 \pm m/p)^k is indistinguishable from 1 for any realistic table. The speed is the problem: a degree-4 polynomial costs several times more than one multiplication.

What independence buys for chaining

With chaining, expected chain lengths need only universality: at most 1+α1 + \alpha, as the Optimized lesson proved. The longest chain is another matter. For nn keys in nn slots, a fully random function makes the fullest slot hold Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n) keys with high probability. How much independence do you need to match that?

DerivationProof
  1. Pr⁡[max load≥t] ≤ m(nt)m−t ≤ m(e nt m)t\Pr[\text{max load} \ge t] \ \le\ m\binom nt m^{-t} \ \le\ m\left(\frac{e\,n}{t\,m}\right)^{t}

    tt keys in one slot. A slot ss receives tt or more keys only if some set of tt keys all hash to ss. For each of the (nt)\binom nt sets, tt-wise independence gives probability m−tm^{-t}. A union bound over the sets and the mm slots, with (nt)≤(en/t)t\binom nt \le (en/t)^t:

  2. max load=O ⁣(log⁡nlog⁡log⁡n)with probability ≥1−1n\text{max load} = O\!\left(\frac{\log n}{\log\log n}\right) \quad\text{with probability} \ \ge 1 - \frac1n

    Logarithmic independence. With n=mn = m and t=⌈3ln⁡n/ln⁡ln⁡n⌉t = \lceil 3\ln n/\ln\ln n \rceil, the right side is n (e/t)t=n−2+o(1)≤1/nn\,(e/t)^t = n^{-2+o(1)} \le 1/n for large nn. A family that is tt-independent for this tt therefore matches a fully random function:

  3. Pr⁡[L≥2n+1] ≤ E[Y](2n+12) = (n−1)/2n+n/2 < 12\Pr\left[L \ge \sqrt{2n} + 1\right] \ \le\ \frac{\E[Y]}{\binom{\sqrt{2n}+1}{2}} \ =\ \frac{(n-1)/2}{n + \sqrt{n/2}} \ <\ \frac12

    Pairwise independence. Let YY count the colliding pairs of keys: E[Y]=(n2)/m=(n−1)/2\E[Y] = \binom n2/m = (n-1)/2 for n=mn = m. A slot with LL keys contributes (L2)\binom L2 pairs on its own, so by Markov's inequality

Predict before you look

You hash n=106n = 10^6 keys into 10610^6 slots with a merely pairwise independent function. Below what maximum load does the bound above guarantee, with probability at least 12\tfrac12?

Show the answer

1415 keys

2×106+1≈1414+1=1415\sqrt{2 \times 10^6} + 1 \approx 1414 + 1 = 1415. Compare a fully random function, whose fullest slot holds about 8 keys at this size, and 15-independence, for which the union bound gives Pr⁡[max load≥15]≤7.7×10−7\Pr[\text{max load} \ge 15] \le 7.7 \times 10^{-7}. The square-root scale is not slack in the proof: Alon, Dietzfelbinger, Miltersen, Petrank and Tardos (1999) showed that universality keeps the expected largest bucket below n+12\sqrt n + \tfrac12, and that for linear maps over a field of square order nn, some sets of nn keys always produce a bucket of n\sqrt n keys.

Linear probing needs exactly five

Linear probing stores keys in the table itself and scans forward from h(x)h(x) to the first free slot. A lookup costs the length of the run of occupied slots through h(x)h(x), and runs grow by merging, so a few unlucky keys slow down their neighbors: primary clustering. Knuth's classic analysis assumed a truly random function. How much independence does the expected O(1)O(1) cost really need?

The proof idea explains the number five. A run of length at least ℓ\ell through h(x)h(x) forces one of a constant number of aligned intervals of length proportional to ℓ\ell, near h(x)h(x), to receive more keys than it has slots, although it expects only an α\alpha fraction of that. A fourth-moment bound makes this probability O(1/ℓ2)O(1/\ell^2). It needs the other keys to be 4-wise independent given h(x)h(x), which is exactly 5-independence.

Over the scales ℓ=2i\ell = 2^i, the expected run length is then ∑i2i⋅O(4−i)=O(1)\sum_i 2^i \cdot O(4^{-i}) = O(1). With only second moments, Chebyshev's tail is O(1/ℓ)O(1/\ell), every scale contributes O(1)O(1), and the log⁡2n\log_2 n scales add up to a logarithm.

Check your understanding

In the analysis of linear probing, why is 4-wise independence of the keys one short?

  1. Linear probing compares keys in groups of five
  2. Five is the smallest independence for which the load factor can exceed 12\tfrac12
  3. The fourth-moment bound for an interval near h(x)h(x) must hold conditioned on the query key's own slot, which uses one more degree of independence
  4. A 4-independent family cannot be evaluated in constant time
Show the answer

C. The fourth-moment bound for an interval near h(x)h(x) must hold conditioned on the query key's own slot, which uses one more degree of independence

The run through h(x)h(x) is located relative to h(x)h(x), so the analysis fixes h(x)h(x) and then needs fourth moments of the other keys' counts: 4-wise independence given one more key's value, that is, 5-independence. Pătraşcu and Thorup showed the extra degree is truly needed by exhibiting 4-independent families with Θ(log⁡n)\Theta(\log n) expected cost.

Simple tabulation: weak on paper, strong in practice

python
import random

class SimpleTabulation:
    """32-bit keys as 4 bytes; one table of 256 random 64-bit words per byte."""
    def __init__(self):
        self.T = [[random.getrandbits(64) for _ in range(256)] for _ in range(4)]

    def __call__(self, x):
        h = 0
        for i in range(4):
            h ^= self.T[i][(x >> (8 * i)) & 0xFF]
        return h                 # use the top l bits for 2^l slots
DerivationSimple tabulation is 3-independent but not 4-independent
  1. h(x)=Ti[xi]⊕(terms that do not involve Ti[xi])h(x) = T_i[x_i] \oplus \big(\text{terms that do not involve } T_i[x_i]\big)

    A unique character frees a key. Suppose that in a set XX of keys, key xx is the only one with character xix_i in position ii. Then Ti[xi]T_i[x_i] enters h(x)h(x) and no other hash in XX; it is a fresh uniform word, so it makes h(x)h(x) uniform and independent of the other hashes of XX:

  2. Pr⁡[h(x)=u, h(y)=v, h(z)=w]=2−3b\Pr\big[h(x) = u,\ h(y) = v,\ h(z) = w\big] = 2^{-3b}

    Three keys always peel. Let x,y,zx, y, z be distinct, and pick a position ii with xi≠yix_i \ne y_i. If zi≠xiz_i \ne x_i, then xix_i is unique there; otherwise zi=xi≠yiz_i = x_i \ne y_i, and yiy_i is unique. Peel that key off. The remaining two keys differ in some position, where both characters are unique. Hence, for all u,v,wu, v, w,

  3. h(a,c)⊕h(a,c′)⊕h(a′,c)⊕h(a′,c′)=0h(a,c) \oplus h(a,c') \oplus h(a',c) \oplus h(a',c') = 0

    Four keys need not peel. Take characters a≠a′a \ne a' for position 1 and c≠c′c \ne c' for position 2, with all other characters equal. In the four keys (a,c),(a,c′),(a′,c),(a′,c′)(a,c), (a,c'), (a',c), (a',c') every table entry appears exactly twice, so the hashes always cancel, and the fourth is determined by the other three:

Think first How can a 3-independent function beat some 4-independent families at linear probing?

kk-independence is a worst-case promise over every family with that property, and a family built to be bad can place its few dependencies exactly where linear probing is fragile. The proofs for tabulation never use 4-independence. They use its structure: hashes become dependent only when keys share characters in a "paired" pattern such as the rectangle above, and few key sets have many such patterns, so a peeling argument recovers almost the same tail bounds as full randomness.

Fast families and the frontier

The fastest provably universal family is multiply-shift (Dietzfelbinger, Hagerup, Katajainen & Penttonen, 1997): for ww-bit keys and m=2ℓm = 2^\ell slots, draw a random odd ww-bit aa and keep the top ℓ\ell bits of a⋅x mod 2wa \cdot x \bmod 2^w. Any two distinct keys collide with probability at most 2/m2/m. Adding a random bb and computing in 2w2w bits gives a strongly universal variant (Dietzfelbinger, 1996).

cpp
#include <cstdint>

// Multiply-shift: 64-bit key -> l-bit slot (1 <= l <= 63); a is a random odd 64-bit number.
inline uint64_t multiply_shift(uint64_t x, uint64_t a, unsigned l) {
    return (a * x) >> (64 - l);   // unsigned overflow is the "mod 2^64"
}

One multiplication and one shift: unbeatable for chaining and for universal hashing in general. Consecutive keys x,x+1,x+2,…x, x+1, x+2, \dots land on an almost arithmetic progression of slots, the kind of structure that hurts linear probing.

Why do weak hash functions usually work anyway? Mitzenmacher and Vadhan (2008) showed that if the keys themselves carry enough randomness (entropy), even a 2-universal function behaves close to a truly random one. Real data is often random enough; adversarial and highly regular data are exactly where weak functions break. Much of practice runs on fast non-cryptographic functions such as MurmurHash and xxHash, which come with no theorem at all.

Key takeaways

  • A kk-independent family makes any kk distinct keys land in independent uniform slots; a random polynomial of degree k−1k-1 over a prime field achieves it with a seed of kk words.
  • Chaining needs only pairwise independence for expected O(1+α)O(1 + \alpha) lookups, but then the longest chain can reach Θ(n)\Theta(\sqrt n); Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n)-independence brings it down to the fully random O(log⁡n/log⁡log⁡n)O(\log n/\log\log n).
  • Linear probing needs 5-independence for expected O(1)O(1) operations (Pagh, Pagh & Ružić), and some 4-independent families give Θ(log⁡n)\Theta(\log n) (Pătraşcu & Thorup), as does multiply-shift on dense keys.
  • Simple tabulation is only 3-independent, yet it gives linear probing O(1/ε2)O(1/\varepsilon^2) expected time, Chernoff-style bucket loads and cuckoo hashing that fails with probability O(n−1/3)O(n^{-1/3}).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You hash with h(x)=(a3x3+a2x2+a1x+a0 mod p) mod mh(x) = (a_3x^3 + a_2x^2 + a_1x + a_0 \bmod p) \bmod m, the aia_i independent and uniform in Zp\Z_p, and p≫mp \gg m. Up to the small rounding of the final  mod  m\bmod\ m, what is the largest kk for which hh is kk-independent?

  1. 3
  2. 4
  3. 5
  4. pp
Show the answer

B. 4

A random polynomial of degree dd is (d+1)(d+1)-independent: any d+1d+1 distinct points determine it by interpolation. A degree-3 polynomial with four random coefficients is 4-independent, and not 5-independent, since its values on 4 keys determine its value on a fifth.

Question 2

With simple tabulation on keys of two characters, h(x1x2)=T1[x1]⊕T2[x2]h(x_1x_2) = T_1[x_1] \oplus T_2[x_2], which statement about the keys acac, adad, bcbc, bdbd is true?

  1. Their four hashes are independent and uniform
  2. Their hashes always XOR to zero, so no three of them can be independent
  3. Any three of their hashes are independent, but the fourth is determined by the other three
  4. They always collide in pairs: h(ac)=h(bd)h(ac) = h(bd)
Show the answer

C. Any three of their hashes are independent, but the fourth is determined by the other three

Each table entry appears in exactly two of the four hashes, so their XOR is 0 and h(bd)h(bd) is fixed by the other three. Simple tabulation is 3-independent: among three distinct keys, some key always has a character unique in its position, which makes its hash independent of the others.

Question 3

Which family guarantees expected O(1)O(1) time per operation for linear probing at load factor 12\tfrac12, on every key set?

  1. Multiply-shift, h(x)=(ax mod 2w)≫(w−ℓ)h(x) = (ax \bmod 2^w) \gg (w - \ell) with aa odd
  2. A random degree-3 polynomial over Zp\Z_p (4-independent)
  3. The Carter–Wegman family ((ax+b) mod p) mod m((ax+b) \bmod p) \bmod m
  4. A random degree-4 polynomial over Zp\Z_p (5-independent)
Show the answer

D. A random degree-4 polynomial over Zp\Z_p (5-independent)

Pagh, Pagh and Ružić proved that 5-independence suffices; Pătraşcu and Thorup showed that some 4-independent families give Θ(log⁡n)\Theta(\log n) expected time on some key sets, so five is exactly the threshold for independence alone. Multiply-shift and Carter–Wegman are only about 2-independent.

Question 4

You hash nn keys into nn slots with chaining. Which guarantee on the longest chain holds for every pairwise independent family?

  1. O(n)O(\sqrt n) with constant probability, and no better in general
  2. O(log⁡n/log⁡log⁡n)O(\log n/\log\log n) with high probability
  3. O(1)O(1) in expectation
  4. O(log⁡n)O(\log n) with high probability
Show the answer

A. O(n)O(\sqrt n) with constant probability, and no better in general

Counting colliding pairs gives a longest chain below 2n+1\sqrt{2n} + 1 with probability at least 12\tfrac12, and Alon et al. exhibited universal families (linear maps over a field of square order) with a bucket of n\sqrt n keys on some inputs. O(log⁡n/log⁡log⁡n)O(\log n/\log\log n) needs about that much independence, or a cleverer family such as simple tabulation.

Further reading

  • M. N. Wegman & J. L. Carter, "New hash functions and their use in authentication and set equality," Journal of Computer and System Sciences 22(3) (1981), 265–279.
  • A. Pagh, R. Pagh & M. Ružić, "Linear probing with constant independence," SIAM Journal on Computing 39(3) (2009), 1107–1120 (STOC 2007).
  • M. Pătraşcu & M. Thorup, "On the k-independence required by linear probing and minwise independence," ICALP (2010); journal version in ACM Transactions on Algorithms (2016).
  • M. Pătraşcu & M. Thorup, "The power of simple tabulation hashing," Journal of the ACM 59(3) (2012), article 14 (STOC 2011).
  • M. Thorup, "High speed hashing for integers and strings," lecture notes, arXiv:1504.06804 (2015).