2 ms·
> There are fully generic methods for constructing (minimal) perfect hash functions [...] However, they tend to use lookup tables to construct the hash itself.
by ot 4y ago
> There are fully generic methods for constructing (minimal) perfect hash functions [...] However, they tend to use lookup tables to construct the hash itself.
To be slightly pedantic, this solution uses a lookup table too, but it's small enough that it fits in a machine integer (and thus can be loaded as an immediate value).
In general, there is an information-theoretic lower bound on the size of the auxiliary data you need to build a perfect hash function, and it's Omega(n) bits for n keys. The constant depends on the load factor, when that is 1 it means that the hashes are in [0, n) and the perfect hash function is called minimal, and the space lower bound is log(e)*n bits
For very small n, brute-forcing like this generally yields good functions. In fact, it is one of the strategies used by gperf.