Hashing and Hash Tables Questions
How hash tables and hash-based structures work internally, and how to reason about their performance and correctness. Covers hash function properties (determinism, uniform distribution, speed, avalanche effect), cryptographic versus non-cryptographic hash choices, collision resolution (separate chaining, open addressing: linear probing, quadratic probing, double hashing, Robin Hood hashing, cuckoo hashing), load factor and amortized-cost resizing, and what makes an object hashable (the __hash__/__eq__ contract, immutability, custom composite keys). Covers hash-map-backed cache design (LRU and LFU eviction, TTL) and thread-safe concurrent hash maps (lock striping, CAS-based updates, safe concurrent resizing). Also covers hash-based structures beyond arrays and strings: consistent hashing for distributed routing and sharding, hash joins, hash-flooding and algorithmic-complexity security attacks and their mitigations, and probabilistic membership/cardinality structures such as Bloom filters, Cuckoo filters, Count-Min Sketch, and HyperLogLog. Excludes using a hash map purely as an optimization trick inside an array or string problem (two-sum, group anagrams, longest substring without repeating characters); that pattern belongs to Arrays, Strings, and Hashing. This topic is about the hash table itself: how it is built, how it fails under skewed or adversarial input, and how it scales.
A production backend experienced a latency spike and long GC pauses. Profiling shows frequent large HashMap resizing causing many allocations and long mark-sweep pauses. How would you investigate the root cause and propose fixes to reduce GC impact and rehash overhead (for example pre-sizing maps, using primitive collections, off-heap storage, or batching inserts)?
Sample Answer
Direct answer
Confirm the pauses correlate with map-growth events, not something else, by checking garbage collection (GC, the runtime's automatic memory reclamation process) logs for pause timing against allocation spikes of large backing arrays. Then treat the fix as an allocation-and-copy problem, not a lookup problem: the goal is fewer, smaller, or altogether avoided resize-triggered array copies, a different root cause and a different fix set from collision-driven O(n) lookup latency.
Structured elaboration
Investigating root cause
- GC logs (or a GC-focused profiler) showing pause times correlated with large object allocations and promotions are the first signal; a
HashMapresize allocates a brand-new, larger backing array and copies every existing entry into it, exactly the kind of large, bursty allocation that triggers longer pauses in a generational collector. - Confirm the correlation is specifically resize events, not something else generating large allocations at the same time, by instrumenting or sampling the map's size and capacity around the pause windows, or by reproducing in isolation: replay the same insert pattern against an isolated map and watch for the same pause signature.
- This is a distinct root cause from collision-driven pathological lookups (a hash-quality problem): here the map's hash function may be perfectly fine, the cost is purely from the mechanics of growing the backing array itself, at scale.
Fixes to reduce GC impact and rehash overhead
Pre-sizing maps: if the eventual size is knowable (or reasonably estimable) up front, construct the map with an initial capacity sized for that target instead of the default. This avoids some or all of the resize-and-copy events entirely, trading a slightly larger upfront allocation for zero rehashing later.
Primitive collections: a standard map of boxed keys and values (for example Integer and Long) allocates every key and value as a separate heap object, so growing the map allocates not just the backing array but a wave of small boxed objects too, all of which the garbage collector has to track. Libraries that provide primitive-specialized maps, avoiding boxing entirely and storing raw integer or long values in flat arrays, cut both the per-entry memory footprint and the number of individual objects the collector has to scan.
Off-heap storage: moving the bulk of a very large map's storage outside the managed heap entirely (a memory-mapped or natively-allocated structure, accessed via a thin on-heap wrapper) removes it from garbage collection's responsibility altogether. This is a bigger architectural change but directly eliminates GC pause contribution from that data structure, at the cost of losing some native ergonomics (type safety, generic collection APIs) and needing explicit memory-management discipline.
Batching inserts: if the map is being built up from a stream of individual inserts with unpredictable total size, batching known-size chunks, and pre-sizing per chunk if the chunk size is known, reduces the number of separate resize events compared to one insert at a time growing the map incrementally from empty.
Worked example
A map expected to hold on the order of several million entries, built with a default small initial capacity, resizes repeatedly by doubling as it grows; each resize allocates a new backing array roughly double the previous size and copies every existing entry into it. The LAST resize before reaching final size is, by construction, copying roughly half of the map's final entry count in one single allocation-and-copy burst, typically the most visible single contributor to a GC pause, and exactly what pre-sizing the map from the start eliminates entirely, since the correctly-sized backing array is allocated once, up front, with zero subsequent copies.
Trade-offs and pitfalls
- Pre-sizing based on a wrong size estimate either wastes memory (oversized) or still triggers resizes (undersized); the fix requires a reasonably reliable size estimate, not a guess.
- Off-heap storage is a significant increase in implementation complexity and loses some safety guarantees the managed heap provides; it is worth it for a genuinely large, GC-pressuring structure, not a reflexive first response to any resize-related pause.
- Switching to primitive collections is a real win for memory and allocation pressure but is a dependency and, often, an API change throughout the codebase that touches that map; plan the migration, do not assume it is a drop-in swap.
Explain how equals() and hashCode() in Java interact and why inconsistent implementations can break hash-based caches and maps. Describe strategies to design key classes for caches which must remain stable across application versions and survive serialization, including avoiding volatile fields and using explicit versioning of key formats.
Sample Answer
Direct answer
Java's equals() and hashCode() are a matched pair by CONTRACT, not by compiler enforcement:
if a.equals(b) is true, a.hashCode() and b.hashCode() MUST also be equal, or a
HashMap/HashSet will silently fail to find an object that equals() says is present, because
lookups only compare within the bucket the hash selects. For cache keys that must survive
application restarts, rolling deploys, and serialization, that same contract needs to hold ACROSS
versions too, which means keeping hashCode()/equals() off any field that can vary between a
deploy that wrote a cache entry and a deploy that reads it, and explicitly versioning the key's
own format.
Structured elaboration
Why an inconsistent implementation breaks hash-based caches and maps. A HashMap places an
entry in the bucket its key's hashCode() selects; a lookup computes the hash of the SEARCH key,
goes straight to that bucket, and only then uses equals() to check candidates within it. If two
objects are equals()-equal but have different hashCode() values, they can land in different
buckets, so a lookup for one will never even consider the other as a candidate, even though the
application considers them the same logical key. This produces exactly the symptom a cache
exhibits when this bug is present: unexplained, intermittent cache misses for keys the
application is certain it already cached.
Designing key classes that remain stable across application versions. The danger is any field
that can differ between the version of the code that WROTE a cache entry and the version that
READS it: a field derived from a build identifier, an ordinal position in an enum that a future
release might reorder, a timestamp captured at construction, or any value influenced by
process-local state. None of these belong in hashCode()/equals() for a cache key meant to
outlive a single deploy; strip the key down to the minimal set of business-identity fields that
are guaranteed to mean the same thing across versions.
Surviving serialization. If cache keys are serialized (written to a distributed cache, or
persisted across a restart), hashCode() must be computed from the DESERIALIZED object's fields,
never from a stored, pre-computed hash value, for the same reason raw persisted hash codes are
unsafe in general: a hash's specific numeric value is an implementation detail of hashCode()'s
CURRENT logic, and that logic can legitimately change between versions even if the underlying
fields do not.
Avoiding volatile fields. A volatile field is one whose value the JVM (Java Virtual Machine, the runtime Java code executes on) guarantees is visible
across threads immediately, which matters for correctness under concurrent access, but has
nothing to do with whether a field is a good input to hashCode(); the actual concern for a
cache key is any field that is MUTABLE at all (volatile or not) after the key enters the cache:
mutating a field hashCode() depends on, after the object is already inserted, moves its logical
identity without moving its physical bucket, orphaning the entry from future lookups.
"Avoid volatile fields" in this context specifically means avoiding fields whose value is subject
to change across the key's lifetime in the cache, not a claim about the volatile keyword itself.
Explicit versioning of key formats. Give every cache key an explicit schema version, most
simply as a literal prefix or field in the key itself (for example "v2:user-id:region:currency"
versus an old "v1:user-id:region"). When the key's shape changes (a field added, removed, or
reinterpreted), bump the version. This guarantees new code looking up a v2 key can never
accidentally match a stale v1 entry that has a different shape, since the version prefix itself
makes the two simply unequal, converting what would otherwise be a silent
wrong-schema-deserialization risk into a clean, safe cache miss that repopulates correctly.
Worked example (Java)
import java.util.HashMap;
import java.util.Map;
final class BrokenCacheKey {
final String userId;
final String buildId;
BrokenCacheKey(String userId, String buildId) {
this.userId = userId;
this.buildId = buildId;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BrokenCacheKey)) return false;
return userId.equals(((BrokenCacheKey) o).userId);
}
@Override
public int hashCode() {
return buildId.hashCode(); // BUG: inconsistent with equals()
}
}
public class BrokenCacheKeyDemo {
public static void main(String[] args) {
BrokenCacheKey k1 = new BrokenCacheKey("u-42", "build-101");
BrokenCacheKey k2 = new BrokenCacheKey("u-42", "build-102");
System.out.println(k1.equals(k2)); // true: same business identity
Map<BrokenCacheKey, String> cache = new HashMap<>();
cache.put(k1, "cached-response-A");
String result = cache.getOrDefault(k2, "CACHE MISS");
System.out.println(result); // different hash -> MISS despite equals() being true
}
}
Running this prints true then CACHE MISS: k1.equals(k2) is true (same userId, the
intended identity), but the cache lookup with k2 misses, because k1 and k2 have different
hashCode() values (derived from the differing buildId, standing in for two different
deployments) and therefore land in different buckets. Fixing hashCode() to depend on userId
only (matching equals()) makes the identical lookup return "cached-response-A" correctly.
For key-format versioning, a separate small demo makes the claim concrete instead of just
asserting it:
import java.util.HashMap;
import java.util.Map;
public class VersionedKeyDemo {
public static void main(String[] args) {
Map<String, String> cache = new HashMap<>();
String v1Key = "v1:u-1:US";
cache.put(v1Key, "old-shape-cached-value");
String v2Key = "v2:u-1:US:USD"; // shape changed: currency field added, version bumped
String result = cache.getOrDefault(v2Key, "CACHE MISS (safe invalidation)");
System.out.println(result);
}
}
Running this prints CACHE MISS (safe invalidation): the version prefix makes v1Key and
v2Key simply unequal strings, so writing under the old shape and reading under the new shape is
a clean cache miss (which safely repopulates) rather than a silent misread of an old-shape value
as if it had the new shape.
Trade-offs and pitfalls
- This bug is silent and intermittent, not a crash, which is exactly why it is dangerous in
production: it surfaces as an unexplained cache-hit-rate drop after a rolling deploy, not as an
obvious error. - Do not conflate "immutable" with "safe for a cache key across versions." A field can be
perfectly immutable within one process's lifetime and still be unsafe across versions, if its
MEANING or presence changes between releases (an enum ordinal is the classic trap: it is
immutable per-instance but not stable across a code change that reorders the enum's
declaration). - Version-prefixing trades a clean invalidation for some wasted cache space immediately after
a version bump (every old-version entry is now permanently unreachable dead weight until it
naturally expires or is evicted); this is normally a good trade for correctness, but worth
accounting for in cache-sizing. - The contract direction only goes one way.
equals() == truemust implyhashCode()
equal; the reverse is not required (hashCode()equal does not implyequals()true, that
is simply an ordinary hash collision, handled normally by the bucket's internal comparison).
Implement a HashSet in Java using open addressing with linear probing. Provide methods add(E key), contains(E key), and remove(E key). Ensure correct handling of tombstones, resizing, and rehashing. Discuss how you will avoid clustering and maintain performance as load factor grows.
Sample Answer
Direct answer
Open addressing stores every entry directly inside the backing array, with no linked nodes. add probes forward from the hashed index until it finds an empty slot or the key itself; remove must leave behind a TOMBSTONE marker rather than a true empty slot, or later lookups for a DIFFERENT key that had to probe past the removed slot would stop early and wrongly report it absent; and resizing has to happen well before the table nears full, because linear probing's performance degrades far faster than chaining's as load factor climbs.
Structured elaboration
Index computation. Spread the hash's bits before reducing modulo capacity (h ^= (h >>> 16) in Java) so that a hashCode() which only varies in its low bits still spreads across the table; skipping this step reproduces primary clustering even with an otherwise fine hash.
add(key). Check the resize threshold BEFORE inserting (kept conservative, 0.5 rather than the 0.75 that works fine for chaining); then linear-probe from the hashed index, remembering the first tombstone slot seen along the way so a reused tombstone is preferred over continuing to a further, truly-empty slot, which keeps live probe chains shorter across repeated insert/remove cycles. Return false if the key is already present.
contains(key). Probe from the hashed index; a true empty slot (never written) means the key cannot be further along this probe chain, since it would have stopped there during insertion too, so contains returns false immediately. A TOMBSTONE, by contrast, must NOT stop the search: the key being searched for may have been placed further along, past this now-removed entry, during its own insertion.
remove(key). On finding the key, overwrite it with the TOMBSTONE sentinel, never with null. Nulling would silently break contains() for any other key whose probe chain had to pass through this slot.
Resize and rehash. Double capacity and re-insert only the LIVE entries, dropping every tombstone in the process. This is also the tombstone cleanup mechanism, not just capacity growth: without it, repeated insert/remove churn would eventually fill the table with dead tombstones even while the live entry count stays low, which is why the resize trigger should be based on live-plus-tombstone count (used), not live count alone.
Avoiding clustering as load grows. Linear probing's expected probe length for a successful search is 21(1+(1−α)21) where α is the load factor, a curve that stays flat at low load and then rises sharply as α→1, unlike chaining's roughly linear degradation; a conservative resize threshold and bit-spreading before modulo are what keep the table on the flat part of that curve.
Worked example
public class ProbingHashSet<E> {
private static final Object TOMBSTONE = new Object();
private static final double LOAD_FACTOR_LIMIT = 0.5;
private Object[] table;
private int size; // live entries
private int used; // live + tombstones
public ProbingHashSet(int initialCapacity) {
table = new Object[initialCapacity];
size = 0;
used = 0;
}
private int indexFor(E key, int capacity) {
int h = key.hashCode();
h ^= (h >>> 16);
return Math.floorMod(h, capacity);
}
public boolean add(E key) {
if ((double) (used + 1) / table.length > LOAD_FACTOR_LIMIT) resize();
int idx = indexFor(key, table.length);
int firstTombstone = -1;
for (int probes = 0; probes < table.length; probes++) {
int i = (idx + probes) % table.length;
Object cur = table[i];
if (cur == null) {
int placeAt = (firstTombstone != -1) ? firstTombstone : i;
table[placeAt] = key;
size++;
if (firstTombstone == -1) used++;
return true;
}
if (cur == TOMBSTONE) {
if (firstTombstone == -1) firstTombstone = i;
continue;
}
if (cur.equals(key)) return false;
}
throw new IllegalStateException("table full despite resize check");
}
public boolean contains(E key) {
int idx = indexFor(key, table.length);
for (int probes = 0; probes < table.length; probes++) {
int i = (idx + probes) % table.length;
Object cur = table[i];
if (cur == null) return false;
if (cur != TOMBSTONE && cur.equals(key)) return true;
}
return false;
}
public boolean remove(E key) {
int idx = indexFor(key, table.length);
for (int probes = 0; probes < table.length; probes++) {
int i = (idx + probes) % table.length;
Object cur = table[i];
if (cur == null) return false;
if (cur != TOMBSTONE && cur.equals(key)) {
table[i] = TOMBSTONE;
size--;
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
private void resize() {
Object[] old = table;
table = new Object[old.length * 2];
size = 0;
used = 0;
for (Object o : old) {
if (o != null && o != TOMBSTONE) {
add((E) o);
}
}
}
public int size() { return size; }
public int capacity() { return table.length; }
public static void main(String[] args) {
ProbingHashSet<Integer> set = new ProbingHashSet<>(4);
System.out.println("add(10): " + set.add(10));
System.out.println("add(10) again (duplicate): " + set.add(10));
System.out.println("contains(10): " + set.contains(10));
System.out.println("contains(99): " + set.contains(99));
for (int i = 1; i <= 10; i++) set.add(i);
System.out.println("size after adding integers 1..10 (10 is a repeat of the first add): " + set.size());
System.out.println("capacity after growth (started at 4): " + set.capacity());
boolean allFound = true;
for (int i = 1; i <= 10; i++) allFound &= set.contains(i);
System.out.println("all 10 distinct elements still found after resize: " + allFound);
// find two distinct, not-yet-inserted keys that hash to the SAME initial slot
Integer a = null, b = null;
int slot = -1;
outer:
for (int cand1 = 1000; cand1 < 5000; cand1++) {
if (set.contains(cand1)) continue;
int s1 = set.indexFor(cand1, set.capacity());
for (int cand2 = cand1 + 1; cand2 < 5000; cand2++) {
if (set.contains(cand2)) continue;
if (s1 == set.indexFor(cand2, set.capacity())) { a = cand1; b = cand2; slot = s1; break outer; }
}
}
System.out.println("collision pair mapping to same initial slot " + slot + ": a=" + a + ", b=" + b);
set.add(a);
set.add(b);
System.out.println("contains(b) before removing a: " + set.contains(b));
set.remove(a);
System.out.println("contains(b) after removing a (tombstone in place): " + set.contains(b));
System.out.println("contains(a) after removing a: " + set.contains(a) + " (must be false)");
}
}
Compiled and run (starting capacity 4):
add(10): true
add(10) again (duplicate): false
contains(10): true
contains(99): false
size after adding integers 1..10 (10 is a repeat of the first add): 10
capacity after growth (started at 4): 32
all 10 distinct elements still found after resize: true
collision pair mapping to same initial slot 8: a=1000, b=1032
contains(b) before removing a: true
contains(b) after removing a (tombstone in place): true
contains(a) after removing a: false (must be false)
1000 and 1032 were found by scanning small integers for a pair that hashes to the same initial slot
after bit-spreading, so 1032's insertion had to probe past 1000's slot. After removing 1000,
contains(1032) still returns true because a tombstone, not null, was left behind; a broken
implementation that nulled the slot instead would have made contains(1032) incorrectly return
false the moment it hit that null. Note the size is 10, not 11: the loop re-adds 10 (already
present from the very first add(10) call), and that duplicate correctly returns false without
increasing size.
Trade-offs and pitfalls
Deleting via null instead of a tombstone is the single most common correctness bug in an open-addressing implementation: it fails silently (wrong answers, not a crash) for unrelated keys rather than the key actually removed. Never rehashing means tombstones accumulate indefinitely under insert/remove churn, degrading lookup performance as if the table were nearly full even when the live entry count is low, which is why the resize decision must watch live-plus-tombstone count, not live count alone.
Explain the concept of load factor in hash tables and how it affects performance and memory usage. Describe the resize (rehash) operation when capacity is doubled and provide an amortized analysis showing that average insertion cost remains O(1). Discuss trade-offs of different resize thresholds (e.g., 0.5 vs 0.75).
Sample Answer
Direct answer
Load factor is the ratio of stored entries to the number of buckets (n / m). A hash table resizes,
allocating a bigger backing array and re-inserting every existing entry, once the load factor crosses
a chosen threshold (commonly 0.75), because letting it climb further makes collisions, and therefore
lookups, get slower.
Structured elaboration
Why load factor matters. For a table using chaining, the average chain length is exactly the
load factor, so a load factor of 0.75 means the average bucket holds 0.75 entries, still effectively
O(1) to scan. Left unchecked (say load factor 20), average chain length would be 20, no longer
meaningfully O(1). For open addressing the effect is sharper: expected probe length grows roughly
like 1 / (1 - load factor), which is fine at 0.5 (about 2 probes) but blows up as load factor
approaches 1 (10 probes at 0.9, effectively unbounded as it approaches 1.0), which is exactly why
open-addressing tables typically resize at a lower threshold than chaining tables do.
What happens during a resize. The table allocates a new backing array, usually double the old
capacity, and re-inserts every live entry by recomputing each one's bucket index against the new
capacity (a key's old bucket index is generally meaningless against a differently-sized table, since
bucket index is hash(key) % new_capacity). This is an O(n) operation, expensive on the one insert
that triggers it, but because it only happens after n has doubled since the last resize, the total
resizing cost summed over n inserts is only O(n), an average (amortized) cost of O(1) extra per
insert (the full amortized-cost proof is worth working through rigorously on its own).
Threshold choice: 0.5 vs 0.75. A lower threshold (0.5) keeps average probe/chain length shorter
at the cost of more frequent resizes and roughly double the wasted (empty) capacity at any given
moment. A higher threshold (0.75, Java HashMap and CPython dict's rough working range) resizes less
often and wastes less memory, at the cost of slightly longer average probes/chains right before a
resize fires. Neither is "correct"; it is a memory-vs-latency trade-off tuned to the expected
workload, latency-sensitive services with memory to spare often pick a lower threshold on purpose.
Worked example
Table starts at capacity 4, threshold 0.75 (resize when entries > 3):
- Insert 1, 2, 3 entries: load factor 0.25, 0.5, 0.75. The 3rd insert leaves load factor exactly at
the threshold; whether that fires a resize depends on whether the check is>or>=capacity*
threshold, an implementation detail worth being precise about in an interview. - Insert the 4th entry: load factor would be 1.0, over threshold, so the table resizes to capacity 8
first, re-inserting all 4 existing entries (now at load factor 0.5 in the new table), then places
the 4th entry.
Trade-offs and pitfalls
A frequent mistake is treating the resize threshold as a fixed universal constant rather than a
tunable trade-off, real systems facing bursty, unpredictable growth sometimes pre-size a table to its
expected final count specifically to avoid paying for resizes during a latency-sensitive burst
(worth working out with real numbers for your expected N). A second pitfall is forgetting that
resizing itself is not free even though it is amortized O(1): a single resize on a very large table
is a real, visible latency spike on whichever operation triggers it, which is exactly the motivation
for incremental/progressive resizing strategies, a design worth exploring in depth on its own, in latency-sensitive
production systems.
Describe minimal perfect hashing and algorithms (e.g., BDZ, CHD) for constructing space-efficient static maps. Explain time and space complexities, construction cost, and practical use cases such as mapping a large static vocabulary to contiguous IDs for embedding tables in ML systems.
Sample Answer
Direct answer
A minimal perfect hash function (MPHF) maps a known, static set of n keys onto exactly n contiguous integers (0 to n-1) with zero collisions and zero wasted table space. Algorithms like CHD (compress, hash, displace) and BDZ build this with a one-time offline construction that is more expensive than building a normal hash table, in exchange for O(1) worst-case lookup at near the theoretical minimum memory per key, which is exactly what a large read-only vocabulary mapping to embedding-table row ids needs.
Structured elaboration
What "minimal perfect" means
- Perfect: no two keys hash to the same slot, no collisions at all.
- Minimal: the table has exactly n slots for n keys, no wasted capacity.
- This is only possible because the key set is known in advance and fixed; an MPHF is built for one specific set, not a general-purpose structure that accepts arbitrary future keys.
How CHD and BDZ build one
- Both use a two-level scheme: a first-level hash function buckets the n keys into n/λ buckets (a small constant λ, typically a handful of keys per bucket); the hard part, finding a collision-free assignment, is then solved independently within each small bucket rather than across the whole key set at once.
- CHD assigns each bucket a small displacement value, searched for locally, that shifts its keys into free slots in the final table. BDZ builds a random hypergraph over the keys and slots and uses a peeling process (repeatedly removing degree-1 nodes) to find a valid assignment.
- Construction time for both is linear in the number of keys, O(n), which is what makes them practical at scale despite being a heavier one-time cost than building an ordinary hash table.
Complexities
- Lookup: O(1) worst case, a small constant number of memory accesses (the first-level hash, then an indexed displacement lookup).
- Space: close to the information-theoretic minimum of log2e≈1.44 bits per key; real CHD/BDZ implementations land somewhat above this bound, typically in the low single-digit bits per key, still far below a general hash table's per-entry overhead.
- Construction: O(n) time and O(n) auxiliary memory during the build, done offline once, not incrementally as keys arrive.
Practical use case: static vocabulary to contiguous ids
A large but fixed vocabulary (every distinct token or item id seen at training time) needs a stable mapping to small contiguous integers so it can index directly into an embedding table's rows. An MPHF gives O(1) lookup from vocabulary key to row index at a fraction of the memory a dict-of-strings would cost, and the vocabulary genuinely is static for the lifetime of a trained model, exactly the assumption an MPHF requires.
Practical comparison of static-structure options
When the key set is fixed and known ahead of time, three structures compete on build-time versus query-time trade-offs:
- Robin Hood hashing: an open-addressing variant where, on insertion, an entry that has probed farther from its ideal slot than the entry currently occupying a candidate slot displaces it. This equalizes probe lengths across the table and keeps worst-case lookup latency low even at high load factors (routinely run at 90%+ full). Cheap to build (still just insertion, no offline solve) and, unlike an MPHF, supports incremental insertion.
- Compact/plain open addressing: the simplest option, cheapest to build, needs more slack capacity (typically 30-50% empty) to keep probe chains short, so it uses more memory per key than the other two for comparable lookup speed.
- Minimal perfect hashing: best possible memory and guaranteed O(1) lookup, but by far the most expensive and least flexible to build; the only one of the three that cannot accept a new key without a full rebuild.
Scenario guidance: choose Robin Hood hashing when the key set will keep growing and build time must stay low; choose plain open addressing when simplicity matters more than squeezing out the last bytes of memory; choose minimal perfect hashing when the key set is genuinely static and memory per key is the dominant cost, such as the embedding-vocabulary case above.
Worked example
For a vocabulary of n=10,000,000 distinct tokens, a dict-based mapping from token to row id pays Python's per-entry object and table overhead on every string key. An MPHF at roughly 2-3 bits/key costs on the order of 2.5-3.75 MB total for the collision-free mapping structure itself, the row-id array on top of that is unavoidable regardless of which structure is used, since every scheme needs to store the n resulting integers somewhere; the MPHF's specific contribution is the mapping structure, not the stored ids.
Trade-offs and pitfalls
- Adding even one new key to an MPHF-backed vocabulary forces a full rebuild; this is a hard architectural constraint, plan for it (batch vocabulary updates, rebuild on a schedule) rather than discovering it in production.
- The O(n) construction cost is linear but the constant factor is real; building an MPHF over hundreds of millions of keys is a genuine offline batch job.
- BDZ's hypergraph-peeling construction can occasionally fail to find a valid assignment on an unlucky random seed and needs to retry with a new hash function; this happens rarely at reasonable bucket sizes but is worth knowing when reading implementation code.
Unlock Full Question Bank
Get access to all Hashing and Hash Tables interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.