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 robust strategies to hash composite keys (tuples of multiple fields) for hash tables. Explain common combination techniques (e.g., multiply-add mixing 31*prev + fieldHash, xor+rotations), handling nulls, order sensitivity, and producing stable hashes across language runtimes.
Sample Answer
Direct answer
Hash each field independently, then combine the per-field hashes with a mixing step, most
commonly the Java-style multiply-add h = 31 * h + fieldHash(field), applied one field at a time
in a fixed order, or an xor-plus-rotate accumulator as an alternative mixing strategy. Handle
null fields with a distinct sentinel value so a missing field never collides with a real value
that happens to hash the same way, and if the key's fields are logically ORDERED (like a
directed edge (from, to)), pick a mixing function that is order-sensitive, since swapping field
order should produce a different combined hash.
Structured elaboration
Multiply-add mixing. Starting from h = 0, fold in each field one at a time:
h = 31 * h + fieldHash(field). The multiplier 31 (an odd prime, chosen historically for being
efficiently computable via a shift-and-subtract on old hardware, and for having good mixing
properties in practice) means each field's contribution is scaled differently depending on its
POSITION, since earlier fields get multiplied by 31 more times than later ones. This is what
makes the combination order-sensitive: combine(a, b) and combine(b, a) generally differ,
because a and b play different roles depending on which position they occupy.
xor+rotate mixing. An alternative: rotate the accumulator by a fixed number of bits, then XOR
in each field's hash: h = rotate_left(h, k) XOR fieldHash(field). This is also order-sensitive
(the rotation happens BETWEEN fields, so which field lands at which rotation phase changes the
result), and distributes bit influence differently than multiply-add; some implementations prefer
it for its simple, fast, branch-free operations.
Handling nulls. A field that is legitimately absent or null must not be silently treated the
same as some default value (empty string, zero) that could also occur as a REAL value, or two
genuinely different composite keys could collide. The fix: define a fixed sentinel hash (for
example, the hash of a marker byte sequence no real field value could ever produce) and use it
whenever a field is null, so (name="Alice", nickname=None) and (name="Alice", nickname="") hash differently, since null and empty string are different values.
Order sensitivity, and when you want it (or don't). If the composite key is inherently
ordered (a directed edge, a version+id pair where the two fields play different roles),
multiply-add or xor-rotate mixing gives you order sensitivity "for free," since each already
depends on field POSITION. If instead the key is a genuinely unordered SET of fields (order
should not matter for equality), you need a different approach: hash each field independently and
combine with a commutative operation, like summing or XOR-ing the individual field hashes
directly (without rotation, which reintroduces order-sensitivity), so permuting the fields leaves
the combined hash unchanged.
Producing stable hashes across language runtimes. A language's BUILT-IN hash function for a
string is frequently randomized per process (to defend against hash-flooding), which makes it
unsuitable as the per-field hash if the combined hash must be reproducible across restarts or
across a different language entirely. Use a fixed, well-specified, content-addressed hash (for
example, a cryptographic digest like SHA-256, or a documented non-cryptographic hash with a
FIXED, published seed) as fieldHash, so the same field VALUE hashes identically regardless of
which process, restart, or language runtime computed it.
Worked example
import hashlib
_NULL_MARKER = b"\x00__NULL__\x00"
def field_hash(value) -> int:
data = _NULL_MARKER if value is None else repr(value).encode("utf-8")
return int.from_bytes(hashlib.sha256(data).digest()[:8], "big")
def combine_multiply_add(fields, mask=(1 << 63) - 1):
h = 0
for f in fields:
h = (31 * h + field_hash(f)) & mask
return h
print(combine_multiply_add(("user-42", None, "US")))
print(combine_multiply_add(("user-42", "", "US")))
print(combine_multiply_add(("alice", "bob")))
print(combine_multiply_add(("bob", "alice")))
Running this: ("user-42", None, "US") and ("user-42", "", "US") produce different combined
hashes (5823293871742902993 versus 8134958508199836266), confirming null and empty string are
never conflated. Swapping field order, combine_multiply_add(("alice", "bob")) versus
combine_multiply_add(("bob", "alice")), produces different hashes (859106286592904078 versus
5917848126298614322), confirming the multiply-add mixing is order-sensitive as intended.
Cross-runtime stability, actually checked (not just claimed)
The claim above, that this scheme is stable across process restarts even though Python's own
built-in string hash() is randomized per process, is worth demonstrating rather than asserting.
This spawns two independent child processes with different PYTHONHASHSEED values and compares
both the built-in hash and the SHA-256-based combined hash between them:
import subprocess
import sys
import os
_CHILD_CODE = '''
import hashlib
_NULL_MARKER = b"\\x00__NULL__\\x00"
def field_hash(value):
data = _NULL_MARKER if value is None else repr(value).encode("utf-8")
return int.from_bytes(hashlib.sha256(data).digest()[:8], "big")
def combine_multiply_add(fields, mask=(1 << 63) - 1):
h = 0
for f in fields:
h = (31 * h + field_hash(f)) & mask
return h
print(hash("user-42"))
print(combine_multiply_add(("user-42", "checkout", "US")))
'''
def run_with_seed(seed):
env = {"PYTHONHASHSEED": str(seed), "PATH": os.environ.get("PATH", "")}
out = subprocess.run([sys.executable, "-c", _CHILD_CODE], env=env,
capture_output=True, text=True, check=True)
builtin_hash, combined_hash = out.stdout.strip().splitlines()
return int(builtin_hash), int(combined_hash)
b1, c1 = run_with_seed(1)
b2, c2 = run_with_seed(999)
print("builtin hash differs across seeds:", b1 != b2)
print("combined hash agrees across seeds:", c1 == c2)
Running this prints builtin hash differs across seeds: True then
combined hash agrees across seeds: True: the two child processes' randomized hash("user-42")
values are different (as expected, since PYTHONHASHSEED changes between them), but the
SHA-256-based combine_multiply_add result for the same composite key is identical in both,
confirming the cross-runtime stability claim rather than just asserting it.
Trade-offs and pitfalls
- Using a language's randomized built-in hash as the per-field hash is the most common bug:
it works fine within one process's lifetime but silently breaks the moment the combined hash
needs to survive a restart, be compared across processes, or be recomputed by a different
language's implementation. - Order sensitivity is a design DECISION, not an automatic property. Confirm whether the
composite key is genuinely ordered (use multiply-add or xor-rotate as shown) or genuinely a set
(use a commutative combination instead); applying the wrong one either silently distinguishes
keys that should be equal, or silently merges keys that should be distinct. - Never let null collapse into a real value's hash. This is a subtle correctness bug: it
usually will not surface in testing until two records that differ only by "field present vs
field null" collide unexpectedly. - The multiplier and rotation amount are tuning choices, not magic constants:
31is a
well-tested convention (used by Java's ownObject.hashCode()combination), but the mixing
quality still depends on the per-field hash itself being well-distributed; a poorfieldHash
undermines even a good combination strategy.
Discuss the trade-offs between choosing a hash table capacity that is a power-of-two (allowing index = hash & (capacity - 1)) versus choosing a prime capacity and using modulo. Consider speed of indexing, distribution quality for bad hash functions, and ways modern implementations mitigate poor low-bit hash quality.
Sample Answer
Direct answer
A power-of-two capacity lets the table find a key's slot with a single bitwise AND (hash & (capacity - 1)), while a prime capacity needs a true modulo operation. The AND is faster, but it only ever looks at the hash's LOW bits, so a hash function with weak low-bit randomness clusters badly against a power-of-two table in a way it would not against a prime-sized one, which is exactly why real implementations that use power-of-two tables also add a step that mixes the hash's higher bits down into the low bits before masking.
Structured elaboration
Speed of indexing
hash & (capacity - 1)is a single, branchless bitwise AND whencapacityis a power of two, which is why array-backed hash tables overwhelmingly default to power-of-two sizes.hash % capacityfor an arbitrary (prime) capacity is a true division/modulo operation, historically notably slower than a bitmask; though the practical gap has narrowed on modern hardware, it remains the reason power-of-two sizing is the default choice when raw indexing speed matters.
Distribution quality for bad hash functions
- The bitmask approach uses ONLY the low log2(capacity) bits of the hash value, so if a hash function's low bits are not well distributed (a common failure mode: multiplying by a constant, or hashing structured data like consecutive integers or aligned memory addresses), a power-of-two table clusters keys into far too few buckets, regardless of how well-distributed the hash's HIGH bits might be.
- A prime-sized table with true modulo uses the hash value's full range in a way that is much more forgiving of a hash function with poor low-bit quality but reasonable overall distribution; prime moduli tend not to share small common factors with structured input patterns the way a power-of-two mask does.
Modern mitigations for poor low-bit quality
- Many production hash tables keep the power-of-two capacity, for the indexing speed, and instead fix the hash function: apply a supplemental spreading step that XORs or mixes the higher bits down into the low bits before masking, so even a hash with weak low bits gets some entropy from its higher bits reflected into the bits that actually get used. Java's
HashMap, for example, applieshash ^ (hash >>> 16)to every key's hash code before masking, for exactly this reason. - CPython's dict and set implementation takes a related but different approach: rather than only fixing the hash, its open-addressing probe sequence itself incorporates the hash value's higher bits across successive probes, so even if the initial masked slot collides due to poor low-bit quality, subsequent probes are informed by bits the first probe ignored, recovering good behavior over the course of a probe chain rather than a single lookup.
Worked example
Consider hashing the values 0,256,512,768,… (a plausible pattern: a field always populated as a multiple of 256, such as a scaled fixed-point value). With a power-of-two capacity of 16 (mask 15): 256mod16=0, so EVERY one of these keys maps to bucket 0, no matter how many there are, total clustering. With a prime capacity of 17: 256mod17=1, so consecutive multiples of 256 land at buckets 0,1,2,3,… (since 256kmod17=kmod17), spreading cleanly across the table instead of collapsing onto one bucket.
Trade-offs and pitfalls
- Choosing prime capacities "to be safe" without knowing whether your hash function actually has weak low bits trades away real, measurable indexing speed for a problem that a good hash function's supplemental mixing step already solves.
- Conversely, assuming a power-of-two table is always safe because "the language's hash function is probably fine" is risky for custom or user-supplied hash functions (a hand-written
hashCodeon a composite key) that were never validated for low-bit quality. - The right question is not "power-of-two or prime" in isolation, it is whether the hash function feeding the table has been checked for exactly the failure mode, poor low-bit distribution, that only power-of-two masking is vulnerable to.
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 streaming pipeline that maintains an approximate top-K frequent items view over a sliding 1-hour window at 100k events/sec. Propose an approach, justify the space/error trade-off you're making versus exact counting, explain how you'd implement the windowing, and how partial results would be aggregated across a distributed set of workers.
Sample Answer
Direct answer
At 100,000 events/sec over a full 1-hour window, exact per-key counting means a hash table sized to however many distinct keys showed up in that hour, which for a high-cardinality dimension (URLs, user IDs, IP addresses, metric tag combinations) is unbounded and can run into gigabytes. The approach instead fixes memory to a small constant using a counting sketch (Count-Min Sketch, Lossy Counting, or Space-Saving), split into fixed-size tumbling sub-windows so the 1-hour sliding view is really "sum the last 60 one-minute buckets," computed independently per worker and merged periodically across the fleet. This is the same mechanism used behind the scenes in observability pipelines that need to surface the top contributors to a metric across a huge space of possible tag values (which endpoint, which customer, which error code is dominating traffic) without ever storing one counter per distinct tag combination.
Structured elaboration
Algorithm choice and the space/error trade-off versus exact counting.
| Structure | Memory | Guarantee | Notes |
|---|---|---|---|
| Exact hash table | grows with distinct-key count, unbounded | perfect | infeasible at this cardinality; a single hour with 50,000,000 distinct keys at roughly 50 bytes/entry (hash bucket + key + counter overhead) already costs about 2.5 GB, and that number keeps growing with cardinality, not with time |
| Count-Min Sketch (CMS) | fixed, width x depth counters | probabilistic: estimate never below the true count, and within epsilon * N of it with probability 1 - delta | merges across workers by simple cell-wise addition, the property this design leans on hardest |
| Lossy Counting | fixed-ish, bounded by 1/epsilon buckets | deterministic: estimate within epsilon * N of true count, using a decaying-bucket prune step | simple to reason about for a single stream, awkward to merge across independently pruned instances |
| Space-Saving | fixed, m counters | deterministic: true count (\le) estimate (\le) true count + N/m, guaranteed to retain any key above a 1/m share | good single-worker top-K tracker, mergeable across workers only with a dedicated procedure that widens the error bound |
The design uses CMS as the structure that actually gets merged across the fleet, because CMS is the only one of the three whose merge is exact arithmetic (summing matching cells produces precisely the sketch you would have gotten by running one CMS over the combined stream); Lossy Counting and Space-Saving are mentioned because they are the natural single-node alternatives an interviewer expects you to know, and either can back a single worker's local top-K view.
Concretely, for a 1-hour window at 100,000 events/sec, (N = 100{,}000 \times 3600 = 360{,}000{,}000) events. Sizing CMS at (\epsilon = 0.0001), (\delta = 0.001):
w = ceil(e / epsilon) = 27,183
d = ceil(ln(1 / delta)) = 7
That is 190,281 counters, about 0.76 MB per sketch at 4 bytes/counter, with an absolute error bound of epsilon * N = 36,000, about 0.01% of the window total, with 99.9% confidence. Against the roughly 2.5 GB exact hash table estimate above, a single 0.76 MB sketch is a compression of over 3,000x; the actual per-worker footprint needed for windowing (60 one-minute buckets, about 45.7 MB per worker) is the more honest number to compare against the exact-table baseline, and it still gives roughly 55x memory reduction (2.5 GB / 45.7 MB), a large win, just not the 3,000x figure a single sketch alone would suggest, in exchange for that bounded, known error instead of a perfect count.
Windowing implementation. A sketch has no native concept of "forget events older than an hour," so the window is built from tumbling sub-windows: each worker keeps 60 separate one-minute CMS instances in a ring buffer. Every minute, the oldest bucket is discarded and a fresh, empty bucket starts absorbing new events; the current "1-hour sliding window" answer at any moment is the cell-wise sum of the 60 retained buckets. This trades exact window boundaries (an event 61 minutes old and one 59 minutes old are treated identically until the whole oldest bucket rolls off) for a simple, cheap, memory-bounded implementation; tightening the boundary means shrinking the bucket size (more, smaller buckets), at the cost of more per-bucket bookkeeping.
Aggregating partial results across a distributed set of workers. Each worker ingests only the events that land on it (no shuffle of raw events by key, which would itself cost more at this rate than the counting), and keeps its own 60-bucket ring. A merge coordinator, on a fixed interval, sums the corresponding one-minute buckets across all workers first (cell-wise addition, cheap: each sketch is under 1 MB), then sums those 60 merged buckets together to get the current global 1-hour sketch. To answer "what are the actual top-K keys" rather than just holding a sketch, each worker also reports its own local top-2K candidate keys (padded beyond K to avoid missing a key whose traffic split evenly across workers), and the coordinator looks up each candidate in the merged sketch to rank the final list.
flowchart LR
A[Ingest ~100k events/sec] --> W1[Worker 1: 60x one-minute CMS buckets]
A --> W2[Worker 2: 60x one-minute CMS buckets]
A --> W3[Worker N: 60x one-minute CMS buckets]
W1 --> M[Merge coordinator: sum buckets across workers, then across the retained hour]
W2 --> M
W3 --> M
M --> Q[Query API: top-K over the merged 1-hour sketch]
Worked example
The epsilon/width/depth/memory figures above are the worked instantiation at this exact scale: N = 360,000,000 events, single-sketch size 0.76 MB (over 3,000x smaller than the roughly 2.5 GB exact table sized for 50 million distinct keys), per-worker 60-bucket footprint 45.7 MB (the real deployed number once windowing is included, still about a 55x memory reduction versus the exact table), and error bound 36,000 events (about 0.01% of the window).
Trade-offs and pitfalls
- Bucket granularity is the real dial, not just epsilon. Shrinking the tumbling bucket from one minute to, say, ten seconds gives a tighter sliding-window boundary but multiplies the number of buckets to retain (360 instead of 60) and the merge work proportionally; this is a genuinely separate trade-off from the CMS epsilon/memory trade-off and both should be tuned independently against what the consumer actually needs.
- CMS only ever overestimates. Because the estimate is the minimum across
dindependent hash rows, unrelated collisions can inflate a low-frequency key's apparent count; this is why the design still keeps a local top-K candidate list per worker rather than trusting a scan of the merged sketch alone to decide who belongs in the final ranking. - A common wrong turn: reaching for one global CMS updated directly by every worker over the network. That reintroduces the exact bottleneck (contention on one shared structure) that sharding by worker was meant to remove; the whole point of CMS's additive merge property is that each worker can update its own sketch with zero coordination and pay the merge cost only periodically, off the hot path.
- Worth calling out explicitly: treating this as "just a metrics-monitoring dashboard problem" undersells it. The identical windowed-sketch-plus-merge pattern is what keeps high-cardinality metrics monitoring affordable in general (finding which tag value dominates a metric without a counter per tag combination), so this design and its trade-offs transfer directly to that framing without any change in mechanics.
Design a distributed hash table (DHT) for a peer-to-peer system (e.g., Chord-like). Describe consistent hashing, node join and leave protocols, routing/lookup complexity, replication strategy for fault tolerance, and how you handle churn and rebalancing.
Sample Answer
Direct answer
A Chord-like distributed hash table (DHT) places nodes and keys on the same hash ring (consistent hashing), but the feature that makes it a routable network rather than just a sharding scheme is the finger table: each node keeps roughly log(N) shortcut pointers to other nodes at exponentially increasing ring distances, so any lookup resolves in O(log N) hops instead of walking the ring one neighbor at a time.
Structured elaboration
Consistent hashing and ring structure. Node and key identifiers come from hashing onto an m-bit ring (2m positions); a key belongs to its immediate clockwise successor node, exactly as in the sharding use of consistent hashing, but here every node is also a router, not just a data holder.
Routing via finger tables. Node n's i-th finger table entry (for i=1,…,m) points to the first node at or after n+2i−1mod2m on the ring. A lookup for key k asks the current node to jump to the farthest finger that does not overshoot k, repeating from there; each hop at least halves the remaining ring distance to the target, giving O(log N) hops total to resolve any key.
Node join. A joining node picks (or is assigned) an id, locates its ring position via a lookup on its own id routed through any known existing node (bootstrapping), takes over the portion of keys that fall between it and its new predecessor (previously owned by its now-successor), and builds its own finger table, either by querying neighbors directly or, more commonly, lazily via periodic stabilization rather than an instantaneous global update.
Node leave and failure, and replication. A voluntary leave can synchronously hand its keys to its successor first; an involuntary failure cannot, which is why fault tolerance depends on two things: each node keeping a SUCCESSOR LIST (several ring-adjacent nodes, not just one), so a lookup can fall through to the next surviving node without the ring needing instant repair, and replicating each key to its node's R closest successors so a single node's failure never loses data outright.
Churn and rebalancing. Rather than synchronously repairing the whole ring on every single join or leave, each node periodically runs stabilization: it re-verifies its successor and predecessor pointers are still correct and fixes them if a neighbor has failed or a new node has inserted itself. This bounds the cost of high churn to incremental, periodic repair instead of a network-wide reorganization per membership event, at the cost of routing tables being transiently stale (still correct enough to make forward progress, if not perfectly up to date) during bursts of churn.
Worked example
For N = 1024 nodes, log2(1024)=10, so any lookup resolves in at most 10 finger-table hops, versus up to 1024 hops walking successor pointers one at a time. Scaling up 1000x to N = 1,000,000 nodes, log2(106)≈19.9, about 20 hops, a roughly 2x increase in hop count for a 1000x increase in network size, which is the entire point of logarithmic routing over linear.
Trade-offs and pitfalls
A common mistake is implementing the finger table for fast routing but keeping only a single successor pointer, which makes the ring fragile to even one node failure until the next stabilization pass repairs it, since a lookup that needs to pass through the failed node's ring slot has no fallback. Another is treating stabilization as instantaneous: during real churn, routing can be transiently incorrect (pointing at a node that has already left), and correctness depends on stabilization eventually converging, not on every single lookup being exactly right at every instant, so client code needs to tolerate and retry a dead-ended hop rather than assume routing is always current.
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.