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.
Design an algorithm to find the first non-repeated word in a very large text file that cannot be fully loaded into memory. Discuss streaming approaches, two-pass algorithms, external sort, or probabilistic methods. Provide a solution that balances memory with accuracy and explain complexity.
Sample Answer
Direct answer
The clean solution is a two-pass, hash-map-based streaming algorithm: pass one builds a hash map
of word to frequency count without holding the file in memory; pass two re-scans the file in
original order and returns the first word whose count is exactly 1. Peak memory is bounded by
the number of DISTINCT words, not the file size, which is the property that makes this work when
the file itself does not fit in RAM. External sort and probabilistic counting are the fallbacks
when even the distinct-word count is too large to hold in memory.
Structured elaboration
Two-pass streaming (the default answer). Read the file once, line by line (or in fixed-size
chunks), splitting into words and incrementing a hash map word -> count. This pass never holds
more than one chunk plus the running map in memory. Read the file a SECOND time, in the same
original order, and return the first word whose final count (from pass one) equals 1. This
requires the file to be re-readable (a normal disk file, or a cursor that can seek back to the
start), which is the usual case for "a file too large for memory" rather than a live network
stream.
Why two passes and not one. A single pass cannot know a word's FINAL count while still
partway through the file, so a naive "return the first word not seen before" is wrong: that word
might repeat later. You need the complete counts from a first pass before you can trust any
word's non-repeating status during a second, order-preserving pass.
When the hash map itself does not fit (extremely large vocabulary). Fall back to external
sort: sort the words (using external merge sort, since the word list itself may not fit in
memory) so identical words become adjacent, then a linear scan of the sorted output counts each
run of identical words. This trades hashing's expected O(n) for sorting's O(n log n), but
removes the requirement that the distinct-word count fit in memory, since sorted runs can be
merged from disk. Recovering "first non-repeated IN ORIGINAL ORDER" from a sorted pass requires
carrying along original position as a secondary sort key, then a small final step to pick the
minimum position among words with count 1.
When exactness itself is negotiable. A Count-Min Sketch gives an approximate frequency count
in sublinear memory in one pass, at the cost of occasionally over-counting a word (never
under-counting), which could cause a truly non-repeated word to be misreported as repeated. Use
this only when a small, disclosed false-negative rate ("might miss the true answer") is an
acceptable trade against a hard memory ceiling that even a hash map of distinct words cannot
meet.
Complexity. Two-pass hashing: O(n) time for n total words across both passes, O(d)
space for d distinct words. External sort: O(n log n) time, O(chunk size) space per merge
step. Probabilistic (CMS): O(n) time, O(sketch size) space, independent of d, with a
disclosed error rate instead of exactness.
Worked example
import io
def first_non_repeated_word_two_pass(file_like):
counts = {}
file_like.seek(0)
for line in file_like:
for word in line.split():
counts[word] = counts.get(word, 0) + 1
file_like.seek(0)
for line in file_like:
for word in line.split():
if counts[word] == 1:
return word
return None
text = "the quick brown fox jumps over the lazy dog the fox runs"
print(first_non_repeated_word_two_pass(io.StringIO(text)))
text2 = "a b a b c"
print(first_non_repeated_word_two_pass(io.StringIO(text2)))
def broken_single_pass_first_sight(text_str):
seen = set()
for w in text_str.split():
if w not in seen:
return w
seen.add(w)
return None
print(broken_single_pass_first_sight(text2))
Running this: against "the quick brown fox jumps over the lazy dog the fox runs", it prints
quick. Manually counting confirms why: the appears 3 times, fox appears 2 times, and every
other word (quick, brown, jumps, over, lazy, dog, runs) appears once; scanning in
original order, quick is the first word whose count is 1. Against the harder case
"a b a b c", the two-pass function prints c, while the naive single-pass "first word not seen
before" check prints a, which is wrong: a looks unrepeated the first time it is seen, and only
a completed count (available after pass one) reveals that a repeats later, exactly the bug
two-pass counting avoids.
Trade-offs and pitfalls
- The most common mistake is trying to answer this in a single pass by returning the first
word not yet in a "seen" set. That is provably wrong whenever a word's later repeat has not
been read yet, as shown above with"a b a b c". - External sort adds
log nfactor but removes the hash-map memory requirement; prefer it
when the number of DISTINCT words is itself too large for memory, not just the raw file size. - A Count-Min Sketch trades exactness for a fixed, disclosed error budget; only acceptable
when the interviewer's stated constraint is a hard memory ceiling that no exact structure can
meet, and only with the error trade-off stated explicitly, not silently assumed. - Re-readability matters: this two-pass approach assumes the file can be scanned a second
time from the start. If the input is a genuinely single-pass stream (no seek), you cannot do
this exactly at all and must accept probabilistic counting or reduce the guarantee to
"first non-repeated among the lastWwords" instead.
You're designing a composite key class in Java (e.g., composed of userId, eventType, and date) to be used as a HashMap key. Describe how you'd implement equals() and hashCode(), handling nulls and performance. Explain why immutability of fields matters and what can go wrong if fields are mutated after insertion into a HashMap.
Sample Answer
Direct answer
hashCode() and equals() must be defined together and stay consistent: two objects that compare
equal MUST produce the same hash code, or a HashMap can insert a key, then fail to find it again
because it looks in the wrong bucket for the "equal" object. For a composite key, that means basing
both methods on the exact same set of fields, handling any nullable field the same way in both, and
caching the hash so repeated lookups aren't recomputing it from scratch.
Structured elaboration
The one-directional contract. The rule is not symmetric: equal objects must share a hash code,
but two objects sharing a hash code do NOT have to be equal (that's an ordinary collision, which the
table's collision-resolution strategy already handles via a follow-up equals() check within the
bucket). Violate the required direction (equal objects, different hashes) and the table breaks
structurally: insertion computes one bucket from the object's hash at that moment, but a later lookup
with an "equal" object computes a different hash, and therefore checks an entirely different
bucket, never finding the entry that is sitting right there in the other one.
Composite keys make this concrete. A key built from multiple fields (say userId, eventType,
date) needs both equals() and hashCode() to consider exactly the same fields, in the same way.
If equals() compares all three fields but hashCode() only hashes userId, two objects that differ
only in date would (correctly) compare unequal but (incorrectly, though harmlessly) share a hash
code, that's just a collision, not a contract violation, since equals() still separates them within
the bucket. The dangerous direction is the reverse: if hashCode() used all three fields but
equals() only compared userId, two objects with different dates but the same userId would compare
EQUAL yet (correctly, given they differ) hash DIFFERENTLY, silently breaking lookups for one of them.
Handling nulls. Any of the three fields (say eventType) may legitimately be null. Hand-rolled
field.hashCode() and field.equals(other.field) calls throw NullPointerException the moment that
field is null. Java's java.util.Objects utility class exists precisely for this: Objects.hash(a, b, c) treats a null argument as contributing 0 to the combined hash instead of throwing, and
Objects.equals(a, b) returns true when both are null, false when exactly one is null, and
delegates to a.equals(b) only when both are non-null. Using these consistently in both methods means
a null eventType behaves the same way in hashCode() as it does in equals(), which is the actual
requirement, not just "doesn't crash."
Performance. Recomputing a hash from three fields on every bucket lookup is wasted work if the
key object is immutable, since the hash can never change after construction. The standard technique
(the one java.lang.String itself uses) is to compute the hash once, in the constructor or lazily on
first use, and store it in a final int field that hashCode() just returns. This turns hashCode()
into an O(1) field read instead of an O(k) recomputation over k fields on every get/put/containsKey
call, which matters once the key class is hashed millions of times a second.
Why immutability matters here too. Even with a perfectly consistent contract, if any field that
feeds hashCode() mutates after the object has already been inserted as a key, the object's hash
changes but its position in the table (chosen using the OLD hash) does not move. A lookup using the
current (post-mutation) state now computes a different bucket than the one the entry actually lives
in. This is exactly the same "moved key" failure that using an inherently mutable type as a key
causes, just triggered here by careless field mutation instead. Marking every field final and
providing no setters makes this class of bug structurally impossible rather than merely unlikely, and
it's also what makes hash-caching in the constructor safe (a mutable field would invalidate the cache).
Worked example (Java)
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
final class CompositeKey {
private final String userId; // may be null
private final String eventType; // may be null
private final String date;
private final int cachedHash; // computed once at construction
CompositeKey(String userId, String eventType, String date) {
this.userId = userId;
this.eventType = eventType;
this.date = date;
this.cachedHash = Objects.hash(userId, eventType, date); // null-safe
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CompositeKey)) return false;
CompositeKey other = (CompositeKey) o;
return Objects.equals(userId, other.userId)
&& Objects.equals(eventType, other.eventType)
&& Objects.equals(date, other.date);
}
@Override
public int hashCode() {
return cachedHash; // O(1), not recomputed per lookup
}
}
public class CompositeKeyDemo {
public static void main(String[] args) {
Map<CompositeKey, String> counts = new HashMap<>();
CompositeKey k1 = new CompositeKey("u1", "click", "2026-01-01");
CompositeKey k2 = new CompositeKey("u1", "click", "2026-01-01"); // distinct object, equal value
counts.put(k1, "first-insert");
System.out.println(k1.equals(k2)); // true
System.out.println(k1.hashCode() == k2.hashCode()); // true
System.out.println(counts.get(k2)); // "first-insert"
// Null field: must not throw, and two null-eventType keys must still be equal
CompositeKey n1 = new CompositeKey("u2", null, "2026-01-02");
CompositeKey n2 = new CompositeKey("u2", null, "2026-01-02");
counts.put(n1, "null-event-insert");
System.out.println(n1.equals(n2)); // true
System.out.println(counts.get(n2)); // "null-event-insert"
}
}
Running this prints true, true, first-insert, true, null-event-insert. The first three lines
confirm the standard contract (equal objects, same hash, lookup by an equal-but-distinct object
succeeds); the last two confirm the null-field case behaves identically instead of throwing or
silently miscomparing.
Trade-offs and pitfalls
The most common real bug is hand-editing equals() (often to add or drop one field during a
refactor) and forgetting to update hashCode() to match, since Java does not enforce this
correspondence at compile time, IDEs' "generate equals and hashCode" helpers exist mainly to keep the
two in sync. Marking all key fields final (and re-deriving cachedHash only in the constructor)
makes the mutation-after-insertion bug structurally impossible rather than just unlikely, and using
Objects.hash/Objects.equals throughout removes null-handling as a place to introduce an
inconsistency between the two methods.
Explain how Python's dict is implemented under the hood: hash table strategy, collision resolution, resizing policy, and the guarantee of insertion-order preservation (Python 3.7+). Discuss why hash collisions can be a security vector and what that implies for services that accept untrusted keys.
Sample Answer
Direct answer
CPython's dict uses open addressing (not chaining) with a compact, two-part layout: a dense array
holding the actual (hash, key, value) entries in INSERTION order, plus a separate, sparser array of
indices into that dense array used purely for hash-based lookup, which is what gives Python
dictionaries their guaranteed insertion-order iteration since Python 3.7, a side effect of this
layout, not a separate feature bolted on.
Structured elaboration
Why two arrays instead of one. Older CPython dicts stored entries directly in the hash-indexed
slots, which wasted a lot of space (most hash tables are kept well below 100% full, so most slots
were empty PyObject* triples). The compact layout instead keeps the DENSE entries array packed with
no gaps (entries appended in insertion order, one per actual key), and a separate SPARSE array
(sized to keep effective load factor around two-thirds) stores small integers that are indices into
the dense array, found via open-addressing probing on the key's hash. This cut memory usage
noticeably for typical dicts and, as a direct consequence, made iteration order equal to insertion
order for free, since iterating the dense array in order IS iterating in insertion order.
Collision handling. On a hash collision in the sparse index array, CPython probes using a
pseudo-random (but deterministic per hash value) perturbation sequence rather than simple linear
probing, designed to avoid the clustering that plain linear probing suffers under, conceptually the same open-addressing family any such table uses, with CPython's own specific probe sequence.
Deletion and tombstones. Deleting a key marks its dense-array slot as a tombstone (rather than
compacting the array immediately, which would be expensive) so open-addressing lookups through the
sparse index continue to work correctly, exactly the same tombstone-marker mechanism any open-addressing table needs on delete; a dict that has seen heavy churn accumulates these until it's next resized, at which
point the dense array is rebuilt compactly with tombstones removed.
Why hash collisions matter for untrusted-key security. Since dict is CPython's universal
namespace/attribute/kwargs mechanism, an attacker who can supply arbitrary STRING keys that all
collide under a predictable hash could, in principle, degrade dict operations toward worst-case
behavior, exactly the hash-flooding attack class. This is precisely why Python salts its string
hashing with a random per-process seed (PYTHONHASHSEED) by default, an attacker who doesn't know
that seed cannot predict which strings will collide, even knowing the hash ALGORITHM perfectly.
Worked example
d = {}
d["z"] = 1
d["a"] = 2
d["m"] = 3
print(list(d.keys())) # insertion order, NOT alphabetical or hash order
del d["a"]
d["a"] = 4 # re-inserted: goes to the END, not back to its old position
print(list(d.keys()))
Running this prints ['z', 'a', 'm'] first (exactly insertion order, confirming the dense-array
mechanism directly), then ['z', 'm', 'a'] after the delete-and-reinsert (confirming that deletion
genuinely removes the key from its ordered position rather than merely marking it invisible in place,
a re-inserted key rejoins the ORDER at the end, as a new append to the dense array, not at its
previous slot).
Trade-offs and pitfalls
A common inaccurate claim is that Python dicts "were always ordered", the ordering guarantee is
specifically a Python 3.7+ language guarantee (it existed as a CPython implementation detail one
version earlier, in 3.6, but was only made a guaranteed part of the language spec in 3.7); code
relying on it should target 3.7+, not assume it holds on arbitrary "modern-ish" Python. A second
pitfall: assuming this ordering means dicts are good for anything requiring frequent REORDERING
(like an LRU (least-recently-used) cache's recency list); a dict's ordering is append/insertion order only, moving an
existing key to the "front" isn't a native dict operation, which is exactly why LRU caches pair a
dict with a genuinely reorderable structure (a doubly linked list) rather than relying on dict
ordering alone.
Advanced system design: Design a multi-region consistent hashing layer for model cache routing where nodes have heterogeneous capacities (weights) and the system must minimize reshuffle when nodes are added or removed. Explain virtual node allocation proportional to weight, hashing strategies for mapping keys, replication policies across regions, and failure handling.
Sample Answer
Direct answer
Weighted consistent hashing changes exactly one thing from the uniform-capacity version: the NUMBER of virtual positions a physical node gets on the ring is made proportional to that node's relative capacity, so a node with twice the capacity claims roughly twice the ring surface. The ring-walk lookup, minimal-movement rebalancing, and failure handling all work identically to the unweighted case once that allocation is set.
Structured elaboration
Virtual node allocation proportional to weight. For nodes with weights wi and a chosen total virtual-node budget Vtotal, assign node i:
vi=∑jwjwi×Vtotal
rounded to an integer. A node with weight 4 in a {4, 2, 1} weight set (total weight 7) is entitled to 4/7 of the total virtual-node budget.
Hashing strategy for mapping keys. Identical to the unweighted ring: hash the key, walk clockwise to the first virtual-node position. Weight only changes how many positions each node occupies, never how a key finds its owner.
Replication across regions. Two common patterns: a single global ring where replica placement skips any candidate node already in a region another chosen replica occupies (region-aware placement), guaranteeing a key's R replicas span at least the required number of distinct regions for regional-failure tolerance; or a separate ring per region plus an explicit cross-region replication policy (e.g. asynchronous replication of a primary region's writes to one designated secondary region), trading immediate cross-region consistency for stronger regional isolation.
Minimizing reshuffle. Adding a node inserts its weight-proportional virtual positions, and only the immediately-following arcs move, exactly as in the unweighted case, but the SHARE that moves to the new node is now proportional to its own weight relative to the total, wnew/∑jwj, rather than a flat 1/(N+1): a node twice as capable should, and does, absorb roughly twice the reshuffled keyspace.
Failure handling. A failed node's virtual positions are removed (or marked unavailable) and its keys fall through to the next clockwise position, the same mechanism as node removal, no special-casing required; combined with region-aware replica placement, a full-region outage still leaves at least one surviving replica for every key as long as replication was configured to span at least 2 regions.
Worked example
Weights {A: 4, B: 2, C: 1}, total weight 7, Vtotal=700:
vA=74×700=400,vB=72×700=200,vC=71×700=100
summing exactly to 700. Node A, at 4x node C's capacity, receives exactly 4x the virtual nodes (400 vs 100) and so is expected to receive roughly 4x C's share of both steady-state traffic and any future reshuffled keys.
Trade-offs and pitfalls
Rounding vi to an integer introduces deviation from the exact target ratio whenever weights don't divide Vtotal evenly (this example's clean 4:2:1 split is the easy case); at a small Vtotal, rounding error is a larger fraction of each node's allocation, so weighted consistent hashing generally needs a larger virtual-node budget than the unweighted case to hit target ratios accurately. Region-aware replica placement adds real routing complexity, the walk must now track distinct REGIONS seen, not just distinct physical nodes, and in a poorly balanced deployment (a region with only one node) it can fail to find R replicas across the required region spread at all, which needs an explicit fallback policy (accept fewer effective replicas and alert, rather than silently under-replicating).
Design a hash table for a low-latency service where even brief lock contention is unacceptable, so a sharded lock-based table is off the table. Walk through how inserts and lookups can proceed without blocking each other, how you would make it safe for a thread to reclaim memory that another thread might still be reading, and how concurrent resizing would work. Compare the result against a sharded lock-based design on the trade-offs that matter.
Sample Answer
Direct answer
A lock-free hash table replaces mutexes with atomic compare-and-swap (CAS) operations on individual pointers or slots, so a thread that loses a race simply retries instead of ever blocking. That freedom brings two hard problems: safely freeing memory a reader might still be traversing, and resizing without a stop-the-world pause, both of which sharded locking sidesteps by simply accepting that one shard's lock holder can occasionally stall everyone else waiting on that same shard.
Structured elaboration
Non-blocking insert and lookup. Represent each bucket as a chain of nodes linked by atomic pointers. Insert performs a CAS on the relevant pointer (the bucket head, or a node's next pointer) to splice in a new node, and if the CAS fails because another thread's concurrent insert won first, the thread simply retries the CAS immediately, it is never suspended waiting on another thread. Lookup only follows pointers and never mutates anything, so it needs no synchronization at all beyond the atomic pointer reads themselves, which is why lookups are truly non-blocking.
Safe memory reclamation. The central hazard is freeing a node another thread is still mid-traversal on. Two standard techniques: hazard pointers, where each thread publishes, in a small shared per-thread slot, which node pointer it is currently about to dereference before it dereferences it; a thread that wants to free a removed node first scans all published hazard pointers and only frees the memory once no other thread has that node marked, otherwise it defers the free onto a retire list and rechecks later. Or epoch-based reclamation, where each thread announces a monotonically increasing global epoch counter value when it begins an operation, and memory removed during epoch E is only actually freed once every thread has advanced past epoch E, meaning nobody can still hold a reference into that stale epoch. Epoch-based reclamation is usually cheaper (an integer read/write versus scanning a hazard array) but reclaims memory less promptly, since one slow or stalled thread delays reclamation for every removed node, not just the ones it happens to touch.
Concurrent resizing. Allocate the new, larger table and migrate buckets from old to new incrementally, using a CAS-based per-bucket migration marker so that any thread, reader, writer, or an idle helper, that touches a not-yet-migrated bucket can help finish moving it (a common lock-free "helping" pattern that avoids any single thread becoming a resize bottleneck). Readers mid-transition either check both tables or follow a forwarding pointer left behind in a migrated bucket, so no key is ever lost or briefly duplicated.
Worked example
Compare the two designs directly:
| Sharded lock-based | Lock-free (CAS plus hazard pointers or epochs) | |
|---|---|---|
| Worst-case latency | One unlucky thread can stall behind a lock holder that gets preempted mid-critical-section on that shard | No thread ever blocks on another; a stalled thread only slows its own retries |
| Implementation complexity | Low, well understood, easy to reason about | High: reclamation and resizing bugs surface only under rare thread interleavings and are notoriously hard to test for |
| Throughput, low contention | Comparable | Comparable, sometimes slightly worse from CAS retry overhead |
| Throughput, heavy contention on one shard/bucket | Serializes on that shard's lock | Degrades to CAS retry storms, but no thread is ever fully blocked, so tail latency is typically better |
| Memory reclamation cost | Trivial: free once outside the critical section | Real, ongoing overhead: hazard-pointer scans or epoch bookkeeping on every operation |
For a service where even brief lock contention is unacceptable, this table is the actual argument for the added complexity: sharded locking still has a genuine worst-case blocking path (a popular shard, or a preempted lock holder), while the lock-free design guarantees every OTHER thread keeps making progress regardless of what one thread is doing.
Trade-offs and pitfalls
Be precise about the guarantee: lock-free means the system as a whole always makes progress, it does not mean any one specific thread is guaranteed to finish in bounded time (a thread could in principle retry indefinitely while others keep winning the race); that stronger, per-thread guarantee is called wait-free and costs considerably more to implement. The reclamation and resizing logic are also where the real engineering cost lives: hazard-pointer scans add a real per-operation cost, epoch-based schemes can leak memory indefinitely if a single thread stalls inside an old epoch and never advances, and resize-helping code is exactly the kind of rare-interleaving logic that passes ordinary tests and fails only under real production concurrency.
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.