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.
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.
Explain what a hash function is and list the properties that make a good general-purpose hash function for hash tables used in data pipelines. Cover determinism, uniform distribution, speed, low collision rate, avalanche effect, and non-adversarial guarantees. Give concrete examples of a poor hash choice and a good hash choice for string keys and why.
Sample Answer
Direct answer
A hash function is good for hash-table use if it is deterministic, distributes keys uniformly across
buckets, computes quickly, and has the avalanche property: changing even one bit of the input flips
roughly half the bits of the output, so similar-looking keys don't cluster together.
Structured elaboration
Determinism. The same key must always produce the same hash within one process/run, or the table
could never find something it already inserted. Note this is compatible with hashing being
randomized across different runs (Python salts string hashing per-process specifically to defeat
hash-flooding attacks), as long as it is stable within a run.
Uniform distribution. Across the actual key population you expect, outputs should spread evenly
over the output range. A hash function can be "random-looking" in general and still distribute one
particular workload badly, e.g. a hash that is uniform over arbitrary strings can still collide badly
if your real keys are all short numeric-looking strings that share a common prefix.
Speed. A hash function runs on every insert, lookup, and delete, so it needs to be cheap,
typically a handful of multiply/xor/shift operations, not something like SHA-256 (see below).
Avalanche effect. A well-mixed hash function should make output bits maximally sensitive to
input bits, so that keys differing by one character (e.g. "user1" vs "user2") land in unrelated
buckets rather than adjacent ones.
Cryptographic vs non-cryptographic choice. Non-cryptographic hash families (FNV, MurmurHash,
xxHash, CityHash) are built purely to satisfy the four properties above as cheaply as possible.
Cryptographic hashes (the SHA family) additionally guarantee collision resistance against an
adversary who is trying to find two inputs with the same output, and preimage resistance
(you can't work backward from the hash to the input). Those extra guarantees cost 10 to 100 times
more CPU per hash and are unnecessary for an ordinary hash table where the only failure mode you
care about is accidental clustering, not a cryptographic attacker trying to forge a signature.
The one place a cryptographic-strength hash earns its cost inside a hash table is exactly the
hash-flooding defense: SipHash (a keyed, non-cryptographic-speed but attack-resistant function) is
used specifically because an attacker who can choose keys should not be able to predict or engineer
collisions even knowing the algorithm, unless they also know the per-process secret key.
Worked example
A concrete case of "uniform in general, bad on your workload": if your keys are internal object IDs
like "obj_00001", "obj_00002", ..., "obj_00999", and your hash function only uses the last
few characters heavily (a genuinely weak, easy-to-write-by-accident hash such as
sum(ord(c) for c in s[-2:])), then IDs sharing the same last two digits collide constantly even
though the hash "looks fine" on random strings. A well-mixed hash (Python's built-in hash(),
MurmurHash, xxHash) processes the whole string and avalanches, so "obj_00001" and "obj_00002"
land in unrelated buckets.
Trade-offs and pitfalls
The most common pitfall is picking a hash function by its name or its Wikipedia reputation
("MurmurHash is a good hash") without checking it against the actual key distribution the table
will see, uniform-on-paper is not the same as uniform-on-your-data. The second common pitfall is
reaching for a cryptographic hash "to be safe," which pays a real latency cost across every
operation for a property (adversarial collision resistance under an unknown-algorithm attacker)
that a table almost never actually needs, since the algorithm is usually knowable and the real
defense against adversarial keys is a per-process secret seed (SipHash-style), not raw
cryptographic strength.
Describe Java's HashMap implementation (post-Java 8): internal table of Node<K,V>, how load factor and threshold work (default loadFactor=0.75), when chains get converted into balanced trees, and how hashCode() and equals() are used. Explain pitfalls such as mutable keys and the effect of bad hashCode implementations.
Sample Answer
Direct answer
Since Java 8, HashMap stores entries in an array of buckets, each normally a linked list of
Node<K,V> objects; it resizes (doubles capacity) once the entry count exceeds capacity times the
load factor (default 0.75), and, as a worst-case safety net, converts ("treeifies") any single
bucket's chain into a small balanced red-black tree once that one bucket grows past 8 entries in a
sufficiently large table.
Structured elaboration
From hashCode to bucket index. HashMap doesn't use a key's raw hashCode() directly as the
index. It first applies a supplemental "hash spreading" step (XOR-ing the hash with itself shifted
right by 16 bits) specifically to mix higher bits into the lower bits, since the actual index
computation is hash & (capacity - 1) (capacity is always a power of two, so this bitmask is
equivalent to, but much cheaper than, a modulo), which only ever looks at the LOW bits of the hash;
without the spreading step, two keys whose hashCodes only differ in high bits would collide on every
capacity that happens to be smaller than that difference.
Load factor and resize. Default loadFactor = 0.75 and default initial capacity 16 means a
resize (doubling capacity, then rehashing every entry) fires once the 13th entry is inserted (16 * 0.75
= 12, so the map resizes on exceeding that threshold). This is the same load-factor/resize mechanism any hash table needs generically; HashMap's specific default is 0.75 with
doubling.
Treeification. Once a single bucket's chain length exceeds TREEIFY_THRESHOLD (8 entries), AND
the table's total capacity is at least MIN_TREEIFY_CAPACITY (64), that one bucket converts from a
linked list to a small red-black tree, bounding THAT bucket's worst-case lookup at O(log n) instead of
O(n). Below capacity 64, HashMap prefers to resize the whole table first (since a small table with one
long bucket is more likely just needing more buckets overall, not a genuinely pathological
distribution), only treeifying once the table is already reasonably large and a bucket is STILL long
after that.
Why hashCode/equals correctness matters more here than almost anywhere else. Every one of the
mechanisms above (bucket index selection, chain traversal, treeified-tree comparison) depends on
hashCode() being consistent with equals() for every key ever inserted; violating that contract doesn't just risk a collision, it can make an entry
permanently unfindable.
Worked example
Inserting keys whose hashCode() values are 0x0000FFFF and 0xFFFF0000 into a HashMap of capacity
16 (capacity - 1 = 0x0000000F): a naive hash & (capacity-1) on the RAW hashCode gives
0x0000FFFF & 0xF = 0xF for the first and 0xFFFF0000 & 0xF = 0x0 for the second, no collision, by
coincidence. But two keys with hashCodes 0x00010000 and 0x00020000 (differing only in bits far
above the low 4 bits actually used by a capacity-16 mask) BOTH give hash & 0xF = 0x0, an unnecessary
collision a wider mask would have avoided if it could see those higher bits at all; the supplemental
hash ^ (hash >>> 16) spreading step exists specifically to fold higher-order bit differences down
into the low bits the mask actually inspects, reducing exactly this class of avoidable collision.
Trade-offs and pitfalls
A common shallow answer describes ONLY the chaining/collision behavior without mentioning the
capacity-must-be-a-power-of-two design (and the resulting bitmask-instead-of-modulo optimization),
or without mentioning that treeification requires BOTH a long chain AND a sufficiently large table,
stating it as if any 8-entry chain treeifies regardless of table size overstates the mechanism and
is a common, checkable inaccuracy.
Explain the LRU (Least Recently Used) cache eviction policy. Describe how to implement LRU with O(1) get and put using common data structures, and why LRU is often a good default for many SRE caching use cases. Mention caveats under bursty access patterns.
Sample Answer
Direct answer
An LRU (least-recently-used) cache always evicts whichever entry hasn't been touched for the longest
time when it needs to make room. A hash map alone can't track "longest untouched" cheaply, and a
linked list alone can't find a given key quickly, so LRU caches pair the two: the map gives instant
lookup, the list gives instant reordering.
Structured elaboration
Why not just a hash map? A plain hash map has no sense of time or usage order at all, entries
are just there or not. To find "the oldest one" you'd have to inspect every entry's last-access time
and take the minimum, an O(n) scan on every eviction.
Why not just a linked list? A linked list ordered by recency (most-recent at the front) makes
"find the least-recently-used entry" trivial, it's always the tail, O(1). But finding a SPECIFIC
key's node, which you need to do on every get, requires walking the list from the front until you
find it, O(n) in the worst case.
Why the pair solves both problems. The map stores key -> node reference, so get(key) jumps
straight to the right list node in O(1) instead of scanning. Having jumped there, moving that node
to the front of the list (marking it "just used") is a handful of pointer updates, O(1), not a
re-sort of the whole list. Eviction is then just "drop whatever's at the tail," also O(1), and
requires removing that same key from the map too, so the two structures never drift out of sync.
Worked example
Capacity-2 cache, inserting A, then B, then accessing A, then inserting C:
- put(A): list is [A] (front=back=A). map: {A}.
- put(B): list is [B, A] (B is now most-recent). map: {A, B}.
- get(A): A moves to the front. list is [A, B]. (B is now least-recently-used, at the tail.)
- put(C): over capacity, evict the tail (B). list becomes [C, A]. map: {A, C}.
Note step 3 is the entire reason this is "least-recently-USED" and not "least-recently-inserted": had
step 3 not happened, B (inserted more recently than A) would have survived and A would have been
evicted instead. Reading a value is itself a "use" that resets the clock.
Why LRU is often a good default for SRE caching use cases
Most real production access patterns exhibit temporal locality: whatever was used recently (a hot
config value, an active user's session, a just-computed result) is disproportionately likely to be
requested again soon, and whatever hasn't been touched in a while genuinely is less likely to be
needed. LRU's eviction rule tracks exactly that signal, recency of use, directly and cheaply: no
per-key frequency counters to maintain (unlike LFU, least-frequently-used), no manual re-tuning as the
workload's hot set shifts over time, since LRU adapts automatically the moment access patterns change.
That combination, cheap to implement (the map-plus-list pairing above), O(1) per operation, and
self-adjusting to whatever is actually hot right now, is why it's the default reached for first, with
more specialized policies (LFU, ARC, a size- or cost-aware eviction rule) reserved for workloads where
a measured access pattern shows LRU's recency-only heuristic is actually a poor fit, such as the bursty
one-time-scan case below.
Trade-offs and pitfalls
Bursty access patterns are the well-known caveat: if a workload scans through a huge sequential range
of keys once each (a full-table scan, say), LRU's "most recently touched" heuristic can be actively
wrong, it will evict genuinely hot, repeatedly-used entries in favor of keeping whatever was touched
most recently by the one-time scan, right up until the scan finally moves on. Recognizing this is the
mark of a stronger answer than one that presents LRU as universally optimal.
Unlock Full Question Bank
Get access to all 41 Hashing and Hash Tables interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.