A two-level perfect hash index is built for one fixed set of keys. The first hash sends keys to N buckets. Construction retries that hash until the sum of squared bucket sizes is bounded by a constant multiple of N. Each bucket of size S then receives S-squared secondary slots and an independently chosen hash with no collisions among its stored keys. A membership query performs two hash computations and compares the exact key in the resulting slot. The comparison matters: an absent key can still land in a occupied slot and must return false. This model accepts unique nonnegative integer IDs smaller than its fixed prime field and uses a deterministic random stream solely to make the demonstration reproducible.
Two-level perfect hashing: exact static case membership
Operational case
Seven case IDs produce thirteen allocated secondary slots in the shown build. Membership for 61 is true; adjacent missing ID 62 is false. The first-level bucket selected for 62 may still contain another case, and its second-level slot may not be empty, so checking only slot occupancy would turn a collision with an absent key into a false positive. The construction has finite retry limits and raises a failure if it cannot find suitable hashes in those budgets. Adding case 149 after publication invalidates the collision-free choices; this immutable index must be rebuilt from the new complete set.
Working Python program
import random
PRIME = 1000003
class StaticCasePerfectHash:
def __init__(self, case_ids):
keys = sorted(set(case_ids))
if any(key < 0 or key >= PRIME for key in keys):
raise ValueError("case ID outside fixed prime field")
self.count = len(keys)
self.first_size = max(1, self.count)
randomizer = random.Random(941)
for _ in range(300):
first_a = randomizer.randrange(1, PRIME)
first_b = randomizer.randrange(PRIME)
groups = [[] for _ in range(self.first_size)]
for key in keys:
groups[((first_a * key + first_b) % PRIME) % self.first_size].append(key)
if sum(len(group) ** 2 for group in groups) <= max(1, 4 * self.count):
break
else:
raise RuntimeError("first-level construction budget exhausted")
self.first_a, self.first_b = first_a, first_b
self.second = []
for group in groups:
width = max(1, len(group) ** 2)
for _ in range(500):
multiplier = randomizer.randrange(1, PRIME)
offset = randomizer.randrange(PRIME)
slots = [None] * width
for key in group:
position = ((multiplier * key + offset) % PRIME) % width
if slots[position] is not None:
break
slots[position] = key
else:
self.second.append((multiplier, offset, slots))
break
else:
raise RuntimeError("second-level construction budget exhausted")
def contains(self, case_id):
if not 0 <= case_id < PRIME:
return False
first = ((self.first_a * case_id + self.first_b) % PRIME) % self.first_size
multiplier, offset, slots = self.second[first]
second = ((multiplier * case_id + offset) % PRIME) % len(slots)
return slots[second] == case_id
def allocated_slots(self):
return sum(len(slots) for _, _, slots in self.second)
if __name__ == "__main__":
index = StaticCasePerfectHash([19, 29, 47, 61, 83, 103, 127])
print("stored:", index.count, "slots:", index.allocated_slots())
print("has 61:", index.contains(61))
print("has 62:", index.contains(62))Output
stored: 7 slots: 13
has 61: True
has 62: FalseTime, space, and tradeoff
Lookup takes O(1) worst-case hash and slot operations under the fixed-width integer model, with O(1) query memory. The accepted first-level squared-size bound limits allocated secondary slots to O(N) for the built set. The classical two-level scheme has expected linear build work with suitable universal hash choices; this bounded teaching implementation makes no build-time guarantee and can fail after its retry budget. Python lists and integer objects occupy more than the conceptual slots. A mutable hash map or linear hashing table is a better fit when IDs change frequently; perfect hashing is attractive for read-heavy snapshots.
Common Mistakes
- Do not skip exact-key comparison for an occupied secondary slot.
- Do not insert into a published static table without rebuilding its hashes.
- Do not claim construction always succeeds within a fixed retry budget.
- Do not send IDs outside the configured integer universe through the hash arithmetic.
Connected lessons
- Hashing
- Data Structures
- Linear hashing: split one bucket at a time as a table grows
- Extendible hashing: split buckets through a shared directory
- Static XOR filters: peel a fingerprint membership index
- Projects
- Quizzes
Compare its update and query contract with BK-trees: search incident labels within edit distance, Vantage-point trees: nearest depots by a metric radius, Centroid decomposition: nearest marked depot on a fixed tree, then complete the structure audit and decision quiz.
