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.
Describe building a token -> id vocabulary for NLP training: counting tokens from arrays of tokens, assigning ids, reserving special tokens (PAD, UNK, BOS, EOS), handling out-of-vocabulary tokens at inference, and memory/storage considerations when vocab size ~50M. Compare using hash maps vs sorted arrays and persistence formats for fast load.
Sample Answer
Direct answer
Build the vocabulary for natural language processing (NLP) model training in two phases: a mutable counting phase (stream every token array through a hash map that tallies frequency), then freeze it into an immutable, id-assigned lookup structure for training and inference. Reserve the first few ids for special tokens, PAD (padding), UNK (unknown / out-of-vocabulary), BOS (beginning-of-sequence), and EOS (end-of-sequence), so every consumer of the vocabulary can hardcode those ids instead of looking them up. At roughly 50 million entries, the STRUCTURE chosen to store the final mapping matters far more for memory and load time than the counting logic itself.
Counting tokens and assigning ids
Stream through the training corpus's token arrays, incrementing a count in a hash map keyed by token string. Once counting finishes, apply a frequency cutoff (drop tokens seen fewer than some minimum number of times) to bound vocabulary size, then assign ids in a fixed order, most commonly by descending frequency, so common tokens get low ids; this also tends to compress better downstream, since low ids repeat more often in a frequency-skewed corpus.
Reserving special tokens
Special tokens need a small, fixed set of ids that never collide with a real corpus token and never depend on which corpus happened to be used for training:
- PAD (padding): fills unused positions in a fixed-length batch so every sequence in a batch has equal length; typically id 0 so padded positions can be masked cheaply.
- UNK (unknown): the fallback id for any token encountered at inference that isn't in the vocabulary.
- BOS (beginning-of-sequence): marks where a sequence starts, useful for generation and for models needing an explicit start signal.
- EOS (end-of-sequence): marks where a sequence ends, so a generative model learns when to stop.
Reserve these before assigning any corpus-derived ids, so their meaning stays stable across vocabulary rebuilds even if the corpus changes.
Handling out-of-vocabulary tokens at inference
A token seen at inference that never appeared (or fell below the training cutoff) has no assigned id. The simplest handling maps it to UNK's id and accepts the information loss. A stronger approach used by most modern pipelines is subword tokenization (byte-pair encoding or WordPiece): tokens are built from smaller sub-units, so a genuinely novel word usually still decomposes into known pieces rather than becoming one opaque UNK, which is why subword vocabularies handle open-ended text far better than whole-word vocabularies.
Memory and storage at roughly 50 million entries: hash maps vs sorted arrays
A hash map keyed by token string needs, per entry: a stored hash, a pointer to the key string (heap-allocated, variable length), the id, and spare capacity (load-factor headroom, typically kept below 0.7) to keep lookups fast. A sorted array of (hash, id) pairs, searched with binary search instead of hashing, is far more compact, since it needs no pointer indirection and no load-factor slack:
bytesarray=n×(hash_bytes+id_bytes)
For n = 50,000,000 with an 8-byte hash and a 4-byte id, that is 50,000,000 x 12 bytes = 600,000,000 bytes, about 600 MB (572 MiB). A hash map's per-entry cost is roughly:
byteshashmap≈load factorn×entry_bytes
With a typical entry cost of 24 to 32 bytes (hash, id, and a pointer to the string) and a load factor of 0.5 to 0.7, that works out to roughly 1.7 to 3.2 GB for the same 50 million entries, several times the sorted array's footprint, purely from pointer indirection and load-factor slack. This is a formula-based engineering estimate, not a measured benchmark of any specific library implementation.
Persistence format for fast load
A sorted array of fixed-width records maps directly onto a flat binary file: loading it is a single memory-map call, and binary search needs no deserialization step at all. A hash map is usually serialized as a list of key-value pairs and has to be walked and reinserted into fresh buckets on load (rehashing), which is both slower and momentarily doubles memory during the rebuild. For a static, read-only, roughly 50-million-entry vocabulary that never changes after training, a memory-mapped sorted array (or a minimal perfect hash function built once offline) is usually the better production choice; a hash map is the right tool for the mutable COUNTING phase, not for the frozen artifact that gets shipped.
Trade-offs and pitfalls
- Shipping a hash map as the FINAL served artifact (rather than only using it during counting) is the most common mistake: it optimizes for a mutability no longer needed and pays for it in memory and cold-start latency.
- Binary search on a sorted array costs O(log n) per lookup (log2(50,000,000)≈26 comparisons) versus O(1) average for a hash map; for 50 million entries this is still fast in absolute terms, but it's a real trade-off if vocabulary lookup sits on a hot path.
- Forgetting to reserve special-token ids before assigning corpus ids means a vocabulary rebuild (a different corpus, a different frequency cutoff) can silently shift what PAD, UNK, BOS, or EOS mean, a subtle and hard-to-detect training bug.
Implement a hash table from scratch (Java or C++) using open addressing with double hashing. Support insert, get, delete, and dynamic resizing. Describe handling of tombstones on delete, rehashing strategy during resize, and argue about amortized O(1) complexity. Include considerations for production concurrency.
Sample Answer
Approach
Open addressing stores every entry directly inside one flat array (no linked chains); on a collision, double hashing computes a second, independent probe step so different keys that collide at the same starting slot still spread out across the table instead of clustering along a fixed stride. Concretely, slot i for probe attempt p is (h1(key) + p * h2(key)) mod capacity, where h2 is forced to never be zero and, with a prime table capacity, is guaranteed to eventually visit every slot. Deletion cannot simply null out a slot, because later entries may have probed past that slot to resolve their own collision; nulling it would break their probe chain and make get stop early and report them missing. The fix is a tombstone: a special "deleted, but keep probing past me" marker distinct from both "live entry" and "truly empty."
Code (Java)
public class DoubleHashTable {
private static final Object TOMBSTONE = new Object();
private Object[] keys;
private Object[] values;
private int capacity;
private int size; // live entries
private int used; // live entries + tombstones, drives resize
public DoubleHashTable(int capacity) {
this.capacity = capacity;
this.keys = new Object[capacity];
this.values = new Object[capacity];
}
private int h1(Object key) {
return (key.hashCode() & 0x7fffffff) % capacity;
}
private int h2(Object key) {
int h = key.hashCode();
return 1 + ((h & 0x7fffffff) % (capacity - 1)); // never 0
}
public void put(String key, Integer value) {
if ((double) (used + 1) / capacity > 0.6) resize();
int idx = h1(key), step = h2(key), firstTombstone = -1;
for (int probe = 0; probe < capacity; probe++) {
int slot = (idx + probe * step) % capacity;
if (keys[slot] == null) {
int target = (firstTombstone != -1) ? firstTombstone : slot;
if (keys[target] == null) used++;
keys[target] = key; values[target] = value; size++;
return;
} else if (keys[slot] == TOMBSTONE) {
if (firstTombstone == -1) firstTombstone = slot;
} else if (keys[slot].equals(key)) {
values[slot] = value;
return;
}
}
throw new IllegalStateException("table full, resize invariant violated");
}
public Integer get(String key) {
int idx = h1(key), step = h2(key);
for (int probe = 0; probe < capacity; probe++) {
int slot = (idx + probe * step) % capacity;
if (keys[slot] == null) return null;
if (keys[slot] != TOMBSTONE && keys[slot].equals(key)) return (Integer) values[slot];
}
return null;
}
public boolean delete(String key) {
int idx = h1(key), step = h2(key);
for (int probe = 0; probe < capacity; probe++) {
int slot = (idx + probe * step) % capacity;
if (keys[slot] == null) return false;
if (keys[slot] != TOMBSTONE && keys[slot].equals(key)) {
keys[slot] = TOMBSTONE; values[slot] = null; size--;
return true;
}
}
return false;
}
private void resize() {
Object[] oldKeys = keys, oldValues = values;
capacity = nextPrime(capacity * 2);
keys = new Object[capacity]; values = new Object[capacity];
size = 0; used = 0;
for (int i = 0; i < oldKeys.length; i++) {
if (oldKeys[i] != null && oldKeys[i] != TOMBSTONE) {
put((String) oldKeys[i], (Integer) oldValues[i]);
}
}
}
private static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false;
return true;
}
private static int nextPrime(int n) {
int candidate = Math.max(n, 2);
while (!isPrime(candidate)) candidate++;
return candidate;
}
public int size() { return size; }
public int capacity() { return capacity; }
public static void main(String[] args) {
DoubleHashTable t = new DoubleHashTable(7);
t.put("a", 1); t.put("b", 2); t.put("c", 3);
System.out.println("get a -> " + t.get("a"));
System.out.println("get missing -> " + t.get("zzz"));
t.delete("b");
System.out.println("get b after delete -> " + t.get("b"));
t.put("d", 4);
System.out.println("get d after reusing tombstone slot -> " + t.get("d"));
System.out.println("get a still resolves past tombstone -> " + t.get("a"));
for (int i = 0; i < 30; i++) t.put("k" + i, i * 10);
System.out.println("size after bulk insert -> " + t.size() + " capacity -> " + t.capacity());
boolean allCorrect = true;
for (int i = 0; i < 30; i++) if (!Integer.valueOf(i * 10).equals(t.get("k" + i))) allCorrect = false;
System.out.println("all 30 post-resize keys correct -> " + allCorrect);
System.out.println("c survived resize -> " + (t.get("c") == 3));
System.out.println("b stays deleted after resize -> " + (t.get("b") == null));
}
}
Output (compiled with javac and executed as shown; starting capacity 7):
get a -> 1
get missing -> null
get b after delete -> null
get d after reusing tombstone slot -> 4
get a still resolves past tombstone -> 1
size after bulk insert -> 33 capacity -> 79
all 30 post-resize keys correct -> true
c survived resize -> true
b stays deleted after resize -> true
Key points
- Tombstones on delete: a deleted slot is marked with a distinct
TOMBSTONEsentinel (notnull), sogetkeeps probing past it instead of stopping early, whileputis free to reclaim that slot for a brand-new key. The demo confirms both halves:get("b")correctly returnsnullafter delete, andget("a")still resolves even though its probe sequence now passes throughb's tombstone. - Rehashing strategy during resize: the table grows to the next prime at least double the old capacity (kept prime so
h2's stride never shares a factor with the table size), and every live entry is walked and re-inserted through the normalputpath; tombstones are dropped rather than copied, since a resize is exactly the natural point to reclaim their space. This is whyused(live plus tombstones) rather thansize(live only) drives the resize trigger: a table can fill up with tombstones alone and still needs to compact even thoughsizelooks small. - Amortized O(1) argument: each resize costs (O(n)) (every live entry is rehashed once), but a resize only fires after roughly doubling the entries admitted since the last one, so the total rehashing work after (n) inserts is bounded by (n + n/2 + n/4 + \cdots < 2n), a constant multiple of (n). Spread over (n) inserts, that is (O(1)) amortized per insert, on top of the already-(O(1))-average probe cost.
- Production concurrency: this implementation is single-threaded only. Making open addressing thread-safe is harder than chaining, because a resize physically relocates every entry, so a reader mid-probe during a concurrent resize can land on a slot that no longer means what it did. Practical options are a single coarse lock around every operation (simple, but serializes all access), sharding into N independently-locked sub-tables (much better throughput, standard production pattern), or a lock-free design with versioned/CAS slots and a copy-on-resize scheme, which is substantially more complex to get correct and is usually reached for only when a proven mature implementation (like
java.util.concurrent.ConcurrentHashMap, which uses chaining internally rather than open addressing for exactly this reason) is not applicable to the constraints.
Complexity
- Average case, insert/get/delete: (O(1)), assuming a good hash and load factor kept under the resize threshold (here 0.6) so probe sequences stay short.
- Worst case: (O(n)), a pathological hash or a table nearly saturated with tombstones can force a scan of most of the table.
- Resize: (O(n)) when triggered, (O(1)) amortized per insert overall, per the argument above.
Edge cases
- Deleting then reinserting a different key: must be able to reuse the tombstoned slot (
put("d", 4)above lands wherebwas deleted). - A key whose probe sequence crosses a tombstone left by an unrelated deleted key: must still resolve correctly (
get("a")afterb's deletion). - A table that has accumulated many tombstones without much live growth: resizing on
usedrather thansizeprevents probe sequences from silently degrading toward (O(n)) even while the map looks small. - Deleting a key that was never present: the loop reaches an empty (
null) slot and returnsfalsewithout touching the table.
Design a Bloom filter to deduplicate incoming event IDs in a high-throughput stream before expensive downstream processing. Explain how to choose the bit array size m and number of hash functions k for expected n items and target false positive rate p. Discuss persistence, reset strategy, and trade-offs compared to using a full hash set.
Sample Answer
Direct answer
A Bloom filter trades a small, tunable false-positive rate for O(1)-per-check membership testing in a fixed, sublinear amount of memory (independent of each item's actual size), with the guarantee that it never produces a false negative. That is exactly the right trade for "skip expensive downstream processing if we've probably already seen this event id": the cost of a rare, bounded-rate mistake (redundantly reprocessing a genuinely new event misclassified as a duplicate) is far cheaper than storing every event id in full.
Structured elaboration
Given an expected item count n and a target false-positive rate p, the bit array size m and hash-function count k are:
m=−(ln2)2nlnp
k=nmln2
These fall out of the false-positive rate formula p≈(1−e−kn/m)k: fixing n and m, this expression is minimized over k at k=(m/n)ln2; substituting that back in and solving for m at a target p gives the first formula. In practice, k is rounded to the nearest integer, and instead of computing k fully independent hash functions, two independent hashes h1, h2 are combined via gi(x)=h1(x)+i⋅h2(x)modm for i=0,…,k−1 (the Kirsch-Mitzenmacher construction), which behaves like k independent hashes for this purpose without needing k separate implementations.
Persistence. The filter is just a bitmap, so it serializes trivially: snapshot it to disk or object storage periodically, or back it directly with a memory-mapped file so a process restart does not lose state. Because bits cannot be read back into the original ids, persistence only protects against losing the "have I seen this" answer, not against losing the actual id list; if you need to recover the ids themselves you need a separate log, the filter is not that log.
Reset strategy. Deduplication is usually windowed ("seen in the last 24 hours"), but a plain Bloom filter cannot delete a single item without risking false negatives for other items sharing a bit, so full resets are the only safe removal. A common pattern is time-sliced filters: roll a fresh filter every window (e.g. hourly), check membership against the last N windows' filters, and drop the oldest window's filter once it ages out. If per-item expiry (rather than whole-window expiry) is required, that calls for a Counting Bloom Filter instead, trading more memory per slot for the ability to decrement on removal.
Versus a full hash set. A hash set has zero false positives, but memory scales with the actual bytes of every distinct item stored (a 16-byte UUID plus per-entry hash-map overhead, often 40 to 80 bytes total per entry in typical language runtimes), while the Bloom filter's footprint is a small, fixed number of bits per expected item regardless of how large or small each item's own representation is.
Worked example
For n = 1,000,000 expected event ids and a target false-positive rate p = 0.01: m=−(ln2)21,000,000×ln(0.01)≈9,585,059 bits, about 1.14 MiB, and k=1,000,0009,585,059ln2≈6.64, rounded to k = 7 hash positions per event. A full hash set storing 1,000,000 sixteen-byte UUIDs at roughly 50 bytes/entry with overhead would need on the order of 50 MB, over 40x the Bloom filter's 1.14 MiB, at the cost of accepting that about 1% of genuinely new event ids will be misclassified as duplicates and skipped.
Trade-offs and pitfalls
The false-positive rate is only p at the moment the filter holds exactly n items; if the real stream keeps inserting past n (no reset ever fires, or the window sizing was wrong), the effective false-positive rate climbs well above the design target as m stays fixed while the true item count grows, since the bit array saturates toward all-ones. A persisted filter must be reloaded with the exact same m, k, and hash implementation it was built with. If any of those change between versions, deserializing old bits under new parameters produces silently wrong membership answers rather than a crash, a correctness bug that is easy to miss in testing and hard to detect in production unless you actively track the empirical false-positive rate (periodically probing with keys known not to be in the set and comparing the observed hit rate to your target p).
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.
Describe double hashing for open addressing and implement a Python function that generates the probe sequence indices for a given key and table size m. Explain how to choose the second hash function so the probe sequence visits every slot (i.e., h2 relatively prime to m).
Sample Answer
Direct answer
Double hashing resolves a collision by computing the NEXT probe step size from a second hash
function, h2(key), instead of always stepping by a fixed amount, so two keys that collide at the
same first slot follow different probe sequences afterward, avoiding the clustering that plagues
linear and (to a lesser extent) quadratic probing.
Structured elaboration
The probe formula. The i-th probe index is typically (h1(key) + i * h2(key)) % capacity. Unlike
linear probing (step size always 1) or quadratic probing (step size grows as i^2, same for every
key), here the step size itself, h2(key), is different for each key. Two keys that happen to share
the same h1 value only continue to collide with each other if they ALSO happen to share the same
h2 value, a much rarer coincidence, which is exactly why double hashing avoids secondary clustering
(quadratic probing's own weak point: same first collision implies the identical full probe sequence
for every colliding key).
The one hard constraint: h2 must be coprime with the table capacity. If h2(key) and capacity
share a common factor g > 1, the probe sequence (h1 + i*h2) % capacity only ever visits
capacity / g distinct slots before repeating, no matter how many times you probe, so it can miss
slots that are genuinely empty. The standard fix is to guarantee h2(key) is always coprime with the
capacity, either by choosing capacity to be a prime number (so any h2 in [1, capacity-1] is
automatically coprime with it), or by constructing h2 to always return an odd number when capacity
is a power of two.
Worked example
def h2(key, capacity):
# A standard construction that guarantees coprimality with a power-of-two capacity:
# any odd number is coprime with a power of two.
return 1 + (hash(key) % (capacity - 1)) | 1 # forces the result to be odd
def probe_sequence(key, capacity, limit=None):
h1 = hash(key) % capacity
step = h2(key, capacity)
limit = limit or capacity
seq = [(h1 + i * step) % capacity for i in range(limit)]
return seq
capacity = 16 # power of two
for k in ["alpha", "beta", "gamma"]:
seq = probe_sequence(k, capacity)
print(f"{k}: h1={seq[0]}, step={h2(k, capacity)}, first 5 probes={seq[:5]}, "
f"visits all {capacity} slots exactly once: {len(set(seq)) == capacity}")
Running this shows each key gets its own first slot AND its own step size (since h2 depends on the
key), and confirms len(set(seq)) == capacity is True for every key, i.e. each key's full probe
sequence really does eventually visit every one of the 16 slots exactly once (no slot is skipped, and
none is revisited before all others are covered), which is precisely the guarantee that a coprime
step size provides.
Trade-offs and pitfalls
The pitfall interviewers specifically probe for is picking h2 carelessly, e.g. h2(key) = hash(key) % capacity with no adjustment: if capacity is even and that expression happens to be even too, the
probe sequence gets stuck cycling through only the even-indexed slots (or only odd), silently halving
the table's effective capacity for that key, a subtle bug that passes casual testing (small load
factors rarely reveal it) and only surfaces as mysterious "table full" failures well before the table
is actually full.
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.