TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Perfect Hashing: The FKS Two-Level Scheme

Perfect Hashing: The FKS Two-Level Scheme

A hash table with chaining answers lookups in O(1)O(1) expected time, but an unlucky key can still sit at the end of a long chain. For a static set of keys, known in advance and never changed (a compiler's keyword table, a dictionary in read-only memory, a routing table), one can do better: worst-case O(1)O(1) lookups, with only O(n)O(n) space, built in O(n)O(n) expected time. The construction of Fredman, Komlós and Szemerédi (1984), known as FKS hashing, uses a universal hash family twice and two applications of Markov's inequality. It is a model example of how a Las Vegas algorithm buys a deterministic guarantee for the answers with randomness spent only on construction.

Two facts about universal hashing

Let hh come from a universal family into mm buckets (Universal Hashing), and let nin_i be the number of keys of a fixed nn-key set in bucket ii. The number of colliding pairs is ∑i(ni2)\sum_i \binom{n_i}{2}, and each of the (n2)\binom{n}{2} pairs collides with probability at most 1m\frac1m, so

E[∑i(ni2)]≤1m(n2).\mathbb{E}\Bigl[\sum_i \binom{n_i}{2}\Bigr] \le \frac{1}{m}\binom{n}{2}.
  1. Quadratic space means no collisions. With m=n2m = n^2 the expected number of colliding pairs is at most n(n−1)2n2<12\frac{n(n-1)}{2n^2} < \frac12, so by Markov's inequality the function is collision-free with probability more than 12\frac12. (This is the birthday paradox read backwards.)
  2. Linear space means small squares. With m=nm = n, using ∑ini2=n+2∑i(ni2)\sum_i n_i^2 = n + 2\sum_i \binom{n_i}{2},
E[∑ini2]≤n+2n(n2)=2n−1<2n,\mathbb{E}\Bigl[\sum_i n_i^2\Bigr] \le n + \frac{2}{n}\binom{n}{2} = 2n - 1 < 2n,

so by Markov's inequality ∑ini2<4n\sum_i n_i^2 < 4n with probability more than 12\frac12.

The construction

text
FKS-BUILD(K)                       // K: n distinct keys
0  repeat                          // level 1: n buckets
1      choose h from a universal family into n buckets
2      distribute K into buckets B_0 .. B_{n-1}
3  until sum of |B_i|^2 < 4n       // expected at most 2 tries
4  for i = 0 to n - 1              // level 2: bucket i gets |B_i|^2 slots
5      repeat
6          choose h_i from a universal family into |B_i|^2 slots
7      until h_i has no collision on B_i      // expected at most 2 tries
8      store each key x of B_i in slot h_i(x) of table T_i

FKS-LOOKUP(x)
0  i = h(x)
1  return T_i[h_i(x)] == x         // two hash evaluations, one comparison

Theorem (Fredman, Komlós and Szemerédi, 1984). FKS-BUILD stores nn keys in O(n)O(n) space, takes O(n)O(n) expected time, and every lookup takes O(1)O(1) time in the worst case.

Proof. Each level-1 try succeeds with probability more than 12\frac12, so the expected number of tries is less than 2, each costing O(n)O(n). Bucket ii needs fewer than 2 expected tries, each costing O(ni)O(n_i) to check (hashing nin_i keys into a fresh table, whose ni2n_i^2 slots can be initialised lazily or counted in the space bound), so level 2 takes O(∑ini)=O(n)O(\sum_i n_i) = O(n) expected time. The space is nn level-1 entries plus ∑ini2<4n\sum_i n_i^2 < 4n slots plus O(n)O(n) words for the function descriptions. A lookup evaluates hh and hih_i and compares once. □\square

The scheme is Las Vegas: the result is always a correct perfect hash table; only the construction time is random.

Implementation

The program builds an FKS table for 1200 random 9-digit keys with the family ha,b(x)=((ax+b) mod p) mod mh_{a,b}(x) = ((ax + b) \bmod p) \bmod m and p=231−1p = 2^{31} - 1, records the number of tries, the space and the largest bucket, and checks every stored key and some absent ones.

python · try it yourself
import random

P = 2 ** 31 - 1

def random_hash(m, rng):
    a, b = rng.randrange(1, P), rng.randrange(P)
    return lambda x: ((a * x + b) % P) % m

def fks_build(keys, rng):
    n = len(keys)
    tries1 = 0
    while True:
        tries1 += 1
        h = random_hash(n, rng)
        buckets = [[] for _ in range(n)]
        for x in keys:
            buckets[h(x)].append(x)
        if sum(len(b) ** 2 for b in buckets) < 4 * n:
            break
    tables, tries2 = [], 0
    for b in buckets:
        size = len(b) ** 2
        while True:
            tries2 += 1
            hi = random_hash(max(size, 1), rng)
            slots = [None] * size
            ok = True
            for x in b:
                j = hi(x)
                if slots[j] is not None:
                    ok = False
                    break
                slots[j] = x
            if ok:
                break
        tables.append((hi, slots))
    return h, tables, tries1, tries2, buckets

def fks_lookup(table, x):
    h, tables = table
    hi, slots = tables[h(x)]
    return len(slots) > 0 and slots[hi(x)] == x

rng = random.Random(100)
keys = rng.sample(range(10 ** 8, 10 ** 9), 1200)
h, tables, t1, t2, buckets = fks_build(keys, rng)
n = len(keys)
space = n + sum(len(s) for _, s in tables)
print(f"n = {n}: level-1 tries {t1}, level-2 tries {t2} for {n} buckets ({t2 / n:.2f} per bucket)")
print(f"sum of n_i^2 = {sum(len(b) ** 2 for b in buckets)} (< 4n = {4 * n}), total slots {space} = {space / n:.2f} n")
print(f"largest bucket {max(len(b) for b in buckets)}, empty buckets {sum(not b for b in buckets)}")
present = all(fks_lookup((h, tables), x) for x in keys)
absent = [x for x in rng.sample(range(10 ** 8, 10 ** 9), 3000) if x not in set(keys)]
print(f"all stored keys found: {present}; false hits among {len(absent)} absent keys: "
      f"{sum(fks_lookup((h, tables), x) for x in absent)}")
n = 1200: level-1 tries 1, level-2 tries 1305 for 1200 buckets (1.09 per bucket)
sum of n_i^2 = 2450 (< 4n = 4800), total slots 3650 = 3.04 n
largest bucket 6, empty buckets 441
all stored keys found: True; false hits among 3000 absent keys: 0

The level-2 tries per bucket average well under 2 because most buckets hold 0 or 1 key and succeed at once.

How the level-1 condition behaves

The program draws 200 level-1 functions for 1500 keys and looks at the distribution of ∑ini2\sum_i n_i^2: its mean should be close to 2n−12n - 1 (for this family, which is close to 2-wise independent), and values of 4n4n or more should essentially never happen.

python · try it yourself
import random

P = 2 ** 31 - 1
rng = random.Random(101)
n = 1500
keys = rng.sample(range(10 ** 8, 10 ** 9), n)
values = []
for _ in range(200):
    a, b = rng.randrange(1, P), rng.randrange(P)
    load = [0] * n
    for x in keys:
        load[((a * x + b) % P) % n] += 1
    values.append(sum(c * c for c in load))
mean = sum(values) / len(values)
print(f"sum of n_i^2 over 200 functions: mean {mean:.0f} (bound 2n - 1 = {2 * n - 1}), "
      f"min {min(values)}, max {max(values)}")
print("fraction at or above 4n:", sum(v >= 4 * n for v in values) / len(values))
sum of n_i^2 over 200 functions: mean 3004 (bound 2n - 1 = 2999), min 2868, max 3118
fraction at or above 4n: 0.0

(The sample mean of 200 draws fluctuates by a few units around the true mean, which is at most 2n−12n - 1.) Markov's inequality promised failure probability below 12\frac12; the real distribution is concentrated tightly around its mean, so the first try almost always succeeds. Proofs often use crude inequalities whose only job is to give a constant success probability; the true behaviour is far better.

In C++

FKS construction and lookup in C++ with the same family and a fixed-seed std::mt19937. Each bucket stores its hash parameters and an offset into one shared slot array, so the whole table is three flat arrays.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_set>
#include <vector>

using u64 = std::uint64_t;
const u64 P = 2147483647;                              // 2^31 - 1
std::mt19937 rng(100);

struct Hash { u64 a, b, m; u64 operator()(u64 x) const { return (a * x + b) % P % m; } };
Hash random_hash(u64 m) { return {1 + rng() % (P - 1), rng() % P, m ? m : 1}; }

struct FKS {
    Hash top;
    std::vector<Hash> second;
    std::vector<size_t> offset;
    std::vector<long long> slot;                       // -1 = empty
    bool contains(u64 x) const {
        u64 i = top(x);
        size_t size = offset[i + 1] - offset[i];
        return size && slot[offset[i] + second[i](x)] == (long long)x;
    }
};

int main() {
    const int n = 20000;
    std::vector<u64> keys;
    std::unordered_set<u64> seen;
    while ((int)keys.size() < n) {
        u64 x = 100000000 + rng() % 900000000;
        if (seen.insert(x).second) keys.push_back(x);
    }
    FKS t;
    std::vector<std::vector<u64>> buckets;
    int tries1 = 0, tries2 = 0;
    for (;;) {
        ++tries1;
        t.top = random_hash(n);
        buckets.assign(n, {});
        for (u64 x : keys) buckets[t.top(x)].push_back(x);
        u64 sq = 0;
        for (auto& b : buckets) sq += b.size() * b.size();
        if (sq < 4ULL * n) break;
    }
    t.offset.push_back(0);
    for (auto& b : buckets) t.offset.push_back(t.offset.back() + b.size() * b.size());
    t.slot.assign(t.offset.back(), -1);
    for (int i = 0; i < n; ++i) {
        u64 size = buckets[i].size() * buckets[i].size();
        for (;;) {
            ++tries2;
            Hash h = random_hash(size);
            bool ok = true;
            for (u64 x : buckets[i]) {
                long long& s = t.slot[t.offset[i] + h(x)];
                if (s != -1) { ok = false; break; }
                s = (long long)x;
            }
            if (ok) { t.second.push_back(h); break; }
            for (size_t j = t.offset[i]; j < t.offset[i + 1]; ++j) t.slot[j] = -1;
        }
    }
    int found = 0, false_hits = 0;
    for (u64 x : keys) found += t.contains(x);
    for (u64 x = 1; x <= 100000; ++x) false_hits += t.contains(x);   // keys are >= 10^8
    std::printf("n = %d: level-1 tries %d, level-2 tries %d, slots %zu = %.2f n\n",
                n, tries1, tries2, t.slot.size(), double(t.slot.size()) / n);
    std::printf("stored keys found: %d of %d; false hits among 100000 absent keys: %d\n", found, n, false_hits);
}
n = 20000: level-1 tries 1, level-2 tries 22019, slots 40258 = 2.01 n
stored keys found: 20000 of 20000; false hits among 100000 absent keys: 0

Beyond static sets

FKS hashing is static. Dietzfelbinger, Karlin, Mehlhorn, Meyer auf der Heide, Rohnert and Tarjan (1994) made it dynamic, with worst-case O(1)O(1) lookups and amortized expected O(1)O(1) updates, by rebuilding buckets (and occasionally everything) when they grow. Cuckoo hashing (Pagh and Rodler, 2001) achieves worst-case O(1)O(1) lookups more simply, with two tables and two hash functions; it is treated in Advanced & Succinct Data Structures. For practical static tables, minimal perfect hash functions that use about 2 bits per key or less are built by methods such as CHD and RecSplit; FKS is the theory that showed O(n)O(n) space and O(1)O(1) worst-case lookups are possible at all.

Test yourself

Why does FKS give bucket ii a second-level table of size ni2n_i^2?

  1. To make the total space quadratic
  2. Because a universal function into ni2n_i^2 slots is collision-free with probability more than 1/21/2
  3. Because ni2n_i^2 is always prime
  4. To leave room for future insertions

With m=nm = n buckets and a universal family, what is the bound on E[∑ini2]\mathbb{E}[\sum_i n_i^2]?

  1. nn
  2. Less than 2n2n
  3. n2n^2
  4. nln⁡nn \ln n

What is random in FKS hashing?

  1. The answer of each lookup
  2. Only the construction time; lookups are deterministic and worst-case O(1)O(1)
  3. The space, which can be quadratic
  4. Nothing

Why does the construction retry the level-1 function until ∑ini2<4n\sum_i n_i^2 < 4n?

  1. To guarantee O(n)O(n) total space for the second level
  2. To make lookups faster
  3. To guarantee no empty buckets
  4. Because otherwise the second level cannot be collision-free