Perfect Hashing: The FKS Two-Level Scheme
A hash table with chaining answers lookups in 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 lookups, with only space, built in 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 come from a universal family into buckets (Universal Hashing), and let be the number of keys of a fixed -key set in bucket . The number of colliding pairs is , and each of the pairs collides with probability at most , so
- Quadratic space means no collisions. With the expected number of colliding pairs is at most , so by Markov's inequality the function is collision-free with probability more than . (This is the birthday paradox read backwards.)
- Linear space means small squares. With , using ,
so by Markov's inequality with probability more than .
The construction
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 comparisonTheorem (Fredman, Komlós and Szemerédi, 1984). FKS-BUILD stores keys in space, takes expected time, and every lookup takes time in the worst case.
Proof. Each level-1 try succeeds with probability more than , so the expected number of tries is less than 2, each costing . Bucket needs fewer than 2 expected tries, each costing to check (hashing keys into a fresh table, whose slots can be initialised lazily or counted in the space bound), so level 2 takes expected time. The space is level-1 entries plus slots plus words for the function descriptions. A lookup evaluates and and compares once.
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 and , records the number of tries, the space and the largest bucket, and checks every stored key and some absent ones.
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 : its mean should be close to (for this family, which is close to 2-wise independent), and values of or more should essentially never happen.
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 .) Markov's inequality promised failure probability below ; 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.
#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 lookups and amortized expected updates, by rebuilding buckets (and occasionally everything) when they grow. Cuckoo hashing (Pagh and Rodler, 2001) achieves worst-case 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 space and worst-case lookups are possible at all.
Test yourself
Why does FKS give bucket a second-level table of size ?
- To make the total space quadratic
- Because a universal function into slots is collision-free with probability more than
- Because is always prime
- To leave room for future insertions
With buckets and a universal family, what is the bound on ?
- Less than
What is random in FKS hashing?
- The answer of each lookup
- Only the construction time; lookups are deterministic and worst-case
- The space, which can be quadratic
- Nothing
Why does the construction retry the level-1 function until ?
- To guarantee total space for the second level
- To make lookups faster
- To guarantee no empty buckets
- Because otherwise the second level cannot be collision-free