Every time software looks up a keyword, a command, or a reserved word, it reaches into a hash table — a structure that maps keys to slots in an array using a mathematical function. Most hash tables are built for the unknown: keys arrive at runtime, so the function has to work for anything. That generality comes at a cost: collisions (two keys landing on the same slot) require extra bookkeeping, and the table must be larger than the key set to keep collisions rare.
But sometimes the key set is fixed in advance. A compiler knows its keywords at build time. A DNS resolver stores a static block of domain names. A router ships with a set of port numbers hardwired into firmware. For these cases, doing the extra work once — at construction time — pays off every time a lookup runs.
A minimal perfect hash function (MPHF) does exactly that: given n distinct keys, it maps each one to a unique slot in {0, 1, …, n-1}. The table has no wasted entries and no collision chains. Every lookup is a single array access in time, with zero overhead for collision resolution — the theoretical minimum for a hash-based lookup.
The puzzle is that building such a function is far from obvious. The keys need not be numbers, the slots must be exactly 0 to n-1, and the function must stay fast to evaluate. The answer turns out to involve randomness, graph theory, and a clever multi-level trick.
Comments
Loading comments...