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.
You are on-call when a production service's 95th percentile latency jumps. Root cause: a hash table used for caching was fed adversarial inputs causing long collision chains and O(n) behavior, resulting in CPU saturation. Describe immediate remediation steps to restore availability, a post-incident analysis plan to determine root cause, and the concrete long-term changes you would propose.
Sample Answer
Direct answer
On-call, with p95/p99 latency spiking and CPU pegged: first confirm the symptom (is one specific
endpoint or hash-table-backed component actually the hot path, via CPU profiling or request
tracing), apply an immediate, reversible mitigation to restore service (rate-limit or reject the
suspect traffic pattern), THEN do the slower root-cause work (was this a genuine attack, or an
organic pathological-input pattern), and only after that decide on the durable fix.
Structured elaboration
Step 1: Confirm before you act. A CPU spike correlated with a specific endpoint or a specific
data structure's operations (visible via a CPU profiler showing time concentrated in hash/lookup
code, or via request tracing showing a small number of abnormally slow requests) is the signal to
look for BEFORE assuming "hash flooding" specifically, plenty of other things cause CPU spikes and
tail-latency jumps, jumping straight to a hash-table-specific fix on a hunch risks fixing the wrong
thing while the real cause continues.
Step 2: Stop the bleeding, reversibly. Once the suspect requests/inputs are identified (e.g. a
specific client, IP range, or an endpoint accepting attacker-controlled keys), the fastest safe
mitigation is usually rate-limiting or temporarily rejecting that specific traffic shape, NOT a
code deploy, deploys are slower and riskier to do under active incident pressure than a
traffic-shaping change, which can typically be rolled back just as fast if it turns out to be wrong.
Step 3: Root-cause, now that the immediate fire is out. Was this attacker-controlled (keys chosen
specifically to collide) or an organic pathological pattern (e.g. a legitimate but unusually
uniform/adversarial-shaped dataset from a real customer)? Confirming which changes what "fixed"
means, an organic pattern might need a data-modeling fix, while a genuine attack needs the
seeded-hashing defense.
Step 4: The durable fix, deployed carefully. If root-caused to predictable hashing, the actual
code change (seeded/randomized hashing, or capping per-request key counts, or confirming
treeification is active) goes through normal review and staged rollout, not rushed out under
continued incident pressure, since a hasty hashing change risks a NEW correctness bug (e.g. breaking existing persisted hash-based routing that depended on the old, predictable hash values) that's arguably worse than the original latency issue.
Worked example
A concrete timeline: T+0, alerting fires on p99 latency; T+2min, CPU profile shows 80% of sampled
stack traces inside the request-parsing hash-map's put path for exactly one endpoint; T+4min,
traffic logs show the spike correlates with a burst of requests from one client ID with unusually
large, unusually structured JSON bodies; T+6min, that client ID is rate-limited (a config change, no
deploy), latency recovers within a minute as the offending traffic drains; T+30min (post-recovery, no
longer under pressure), the actual request bodies are pulled and analyzed offline to confirm whether
the keys were deliberately collision-engineered; T+1 day, if confirmed adversarial, a seeded-hashing
fix is written, reviewed, and staged normally.
Trade-offs and pitfalls
The single biggest mistake under this kind of pressure is skipping straight from "CPU is high" to
"ship a hashing fix", without first confirming causation and without an immediate, reversible
mitigation in place, that ordering risks a rushed code change deployed mid-incident (higher risk of
introducing a NEW bug) while the actual traffic pattern causing the spike might not even be
adversarial. A postmortem that only lists "we added SipHash" without describing HOW the on-call
engineer got from symptom to that specific root cause is a weaker artifact than one that shows the
triage reasoning explicitly, that reasoning is exactly what's being evaluated in a scenario like this.
Design a consistent hashing scheme to shard user data across N backend nodes with support for node addition/removal and replication factor R. Explain virtual nodes, ring traversal, replica placement, how to rebalance data with minimal movement, and approaches to handle hot keys.
Sample Answer
Direct answer
Consistent hashing places both nodes and keys onto one ring (a large hash space, e.g. 0 to 2^160-1), and a key belongs to the first node found walking clockwise from the key's own hash position. At real N-node, R-replica scale, the design decisions that make this work are how many virtual positions each physical node is given, how you walk the ring to pick R distinct replicas, and how you bound how much data moves when membership changes.
Structured elaboration
Virtual nodes. Each physical node is hashed into V virtual positions (commonly 100 to a few hundred) instead of one, spreading its ownership across many small, non-contiguous ring arcs rather than a single large one. This does two things at once: it balances load across equal-capacity nodes (many small arcs average out hash-luck variance far better than one big arc would), and it bounds churn on membership change, since only the arcs immediately clockwise of a changed node's OWN virtual positions are affected, not the whole ring.
Ring traversal. get_node(key) hashes the key onto the ring, then finds the first virtual-node position at or after that hash going clockwise (a binary search over sorted virtual positions, O(log(N*V))); the physical node owning that virtual position holds the key.
Replica placement for factor R. Walk clockwise from the key's position, collecting the first R DISTINCT physical nodes encountered, skipping any virtual node that belongs to a physical node already counted. This spreads a key's R replicas across R different machines automatically, with no separate replica-assignment step, but it means the walk must track physical nodes seen, not virtual positions seen, or it can return the same physical node twice.
Minimal-movement rebalancing. Adding a node inserts its V virtual positions onto the ring; only keys that previously belonged to the virtual node immediately following each of those V new positions move to the new node, everyone else keeps their assignment. Going from N to N+1 nodes, the expected fraction of keys that move is about 1/(N+1), a small fraction rather than a full reshuffle, which is the entire advantage over plain modulo hashing (hash(key) % N), where changing N remaps nearly every key.
Hot keys. However evenly the rest of the keyspace is spread, one very popular key still funnels all its traffic to whichever few physical nodes hold its R replicas. Standard mitigations: detect the hot key and replicate it beyond the standard R, spreading reads round-robin across the extra copies, or split it logically (shard a single hot counter into several sub-counters merged on read) so no single physical node absorbs all of its traffic.
Worked example
import hashlib, bisect
from collections import Counter
def h(key):
return int(hashlib.sha256(key.encode()).hexdigest(), 16)
class ConsistentHashRing:
def __init__(self, nodes, vnodes_per_node=100):
self.vnodes_per_node = vnodes_per_node
self.ring, self.sorted_positions = {}, []
for node in nodes:
self.add_node(node)
def add_node(self, node):
for v in range(self.vnodes_per_node):
pos = h(f"{node}#vnode{v}")
self.ring[pos] = node
bisect.insort(self.sorted_positions, pos)
def get_node(self, key):
pos = h(key)
idx = bisect.bisect(self.sorted_positions, pos)
if idx == len(self.sorted_positions):
idx = 0
return self.ring[self.sorted_positions[idx]]
def get_replicas(self, key, r):
pos = h(key)
n = len(self.sorted_positions)
idx = bisect.bisect(self.sorted_positions, pos) % n
replicas, seen = [], set()
total_physical = len(set(self.ring.values()))
i, steps = idx, 0
while len(replicas) < r and len(seen) < total_physical and steps < n:
physical = self.ring[self.sorted_positions[i % n]]
if physical not in seen:
seen.add(physical)
replicas.append(physical)
i += 1
steps += 1
return replicas
# ---- driver ----
nodes = [f"node-{i}" for i in range(5)]
ring = ConsistentHashRing(nodes, vnodes_per_node=100)
keys = [f"key-{i}" for i in range(50000)]
before = {k: ring.get_node(k) for k in keys}
dist = Counter(before.values())
for n in nodes:
print(f"{n}: {dist[n]} ({100*dist[n]/len(keys):.2f}%)")
ring.add_node("node-5")
after = {k: ring.get_node(k) for k in keys}
moved = sum(1 for k in keys if before[k] != after[k])
print(f"keys remapped: {moved} / {len(keys)} = {100*moved/len(keys):.2f}%")
print(f"expected fraction under ideal consistent hashing ~= 1/6 = {100/6:.2f}%")
replicas = ring.get_replicas("key-0", 3)
print(f"replicas for 'key-0' with R=3: {replicas}")
With 5 nodes at 100 virtual nodes each and 50,000 keys, this prints a pre-add distribution of:
node-0: 12934 (25.87%) node-1: 9422 (18.84%) node-2: 9581 (19.16%)
node-3: 9774 (19.55%) node-4: 8289 (16.58%)
against an ideal of 20.00% each, showing that even 100 virtual nodes per physical node leaves real
variance (node-0 is meaningfully over-represented), which is why production rings often use several
hundred virtual nodes per node to tighten this further. Adding a 6th node then produces:
keys remapped: 8479 / 50000 = 16.96%
expected fraction under ideal consistent hashing ~= 1/6 = 16.67%
closely matching the theoretical minimal-movement fraction rather than a full reshuffle. A
replication check for R=3 on one sample key returned 3 distinct physical nodes, confirming the
skip-already-seen-physical-node logic works: ['node-1', 'node-0', 'node-3'].
Trade-offs and pitfalls
Too few virtual nodes (e.g. one per physical node) gives no load-balancing benefit and can leave one node responsible for a hugely disproportionate arc purely by hash luck; too many (thousands per node) balances load further but grows ring metadata and lookup cost. The most common implementation bug is forgetting to deduplicate by PHYSICAL node while walking for replicas, silently returning the same physical node twice as two different replicas and reducing the real replication factor below R without any error being raised.
Hard problem: You must design an in-memory LRU cache for objects with variable sizes (in bytes) and a total memory budget M. Describe data structures and algorithms to support get(key) and put(key, value, size) such that on insertion you evict least-recently-used items until free memory >= size. Focus on complexity and correctness when sizes vary and discuss fragmentation issues.
Sample Answer
Direct answer
With a fixed byte budget M instead of a fixed entry count, the cache needs to know each entry's size, not just its value, so eviction can be driven by "keep evicting least-recently-used entries until enough bytes are free" rather than "evict exactly one entry." An ordered hash map storing key -> (value, size) alongside a running used_bytes counter gives O(1) lookup and O(1) recency reordering, the same as a plain LRU (least-recently-used) cache, plus a loop on insert that evicts entries from the cold end until the new item actually fits.
Structured elaboration
Data structures and algorithm. Keep an ordered map (a doubly linked list plus hash index, collections.OrderedDict in Python or the manual equivalent) from key to (value, size), plus a running total used_bytes. get(key) looks up the value and moves the entry to the most-recently-used end, unchanged from a fixed-count LRU. put(key, value, size) first rejects outright any single item whose size exceeds the entire budget M (no amount of eviction can ever make it fit), then, if the key already exists, subtracts its old size from used_bytes before doing anything else (so growing an existing key does not silently double-count its old footprint), then evicts from the least-recently-used end in a loop, not just once, until used_bytes + size <= M, and only then inserts the new entry and adds its size to the running total.
Correctness when sizes vary. The two places a fixed-count LRU's usual logic breaks for variable sizes are exactly the two the algorithm above handles explicitly: a single large insert may need to evict several small entries, not one, so eviction has to be a loop bounded by the budget check, not a single popitem; and updating an existing key's size (larger or smaller) has to reconcile the byte accounting before the eviction loop runs, otherwise the running total silently drifts from reality.
Code
from collections import OrderedDict
class ByteBudgetLRU:
def __init__(self, max_bytes: int):
self._max_bytes = max_bytes
self._used_bytes = 0
self._store: "OrderedDict[str, tuple]" = OrderedDict() # key -> (value, size)
def get(self, key):
if key not in self._store:
return None
self._store.move_to_end(key)
value, _size = self._store[key]
return value
def put(self, key, value, size: int):
if size > self._max_bytes:
raise ValueError("single item larger than the entire budget")
if key in self._store:
_, old_size = self._store.pop(key)
self._used_bytes -= old_size
while self._used_bytes + size > self._max_bytes:
self._evict_one()
self._store[key] = (value, size)
self._used_bytes += size
def _evict_one(self):
evicted_key, (_, evicted_size) = self._store.popitem(last=False)
self._used_bytes -= evicted_size
return evicted_key
if __name__ == "__main__":
cache = ByteBudgetLRU(max_bytes=100)
cache.put("a", "A" * 10, 40)
cache.put("b", "B" * 10, 30)
print("used bytes ->", cache._used_bytes)
print("get a ->", cache.get("a") is not None) # touches a, making b the LRU item
cache.put("c", "C" * 10, 50) # 70+50=120 > 100, must evict until it fits
print("used bytes after adding c ->", cache._used_bytes)
print("b evicted (LRU) ->", cache.get("b") is None)
print("a survived (was MRU) ->", cache.get("a") is not None)
print("c present ->", cache.get("c") is not None)
try:
cache.put("huge", "H", 500)
raised = False
except ValueError:
raised = True
print("oversized single item rejected ->", raised)
cache.put("a", "A" * 20, 60) # a grows from 40 to 60 bytes
print("used bytes after growing a ->", cache._used_bytes, "(<=100) ->", cache._used_bytes <= 100)
for i in range(20):
cache.put(f"k{i}", i, 15)
print("budget respected after 20 more varied inserts ->", cache._used_bytes <= 100)
Output (executed as shown):
used bytes -> 70
get a -> True
used bytes after adding c -> 90
b evicted (LRU) -> True
a survived (was MRU) -> True
c present -> True
oversized single item rejected -> True
used bytes after growing a -> 60 (<=100) -> True
budget respected after 20 more varied inserts -> True
Complexity
get: O(1) average, a single hash lookup plus a constant-time move in the backing linked list.put: O(1) average work for the insert itself, plus the cost of however many entries it evicts. Each entry can be evicted at most once ever (it is removed from the structure the moment it is evicted), so across any sequence of nputcalls the total eviction work is bounded by n, giving O(1) amortized cost perput, even though a singleputinserting one very large item can, in the worst case, evict many entries at once and cost more than O(1) for that one call.
Trade-offs and pitfalls
- This design tracks a logical byte budget, not physical memory layout, so as implemented here (ordinary in-process objects plus a running counter) there is no physical fragmentation: each entry is its own independent object, and evicting one frees its memory back to the language runtime directly.
- Fragmentation becomes a real concern the moment the cache is backed by a fixed, contiguous byte arena instead (an off-heap buffer or shared-memory region, often chosen specifically to avoid garbage-collection overhead for large cached blobs). Freeing several small, non-contiguous slots by evicting cold entries does not guarantee a new, differently-sized item can actually fit into that freed space, even though the aggregate free-byte count is sufficient, exactly the external-fragmentation problem a general-purpose memory allocator has. The standard production fix is slab allocation (rounding each item up to the nearest of a small set of fixed size classes and only ever placing or evicting within same-size-class slots), which trades a bounded amount of internal fragmentation (wasted space within an oversized slot) for eliminating external fragmentation entirely, since any freed slot in a size class is guaranteed reusable by any other item in that same class.
- A single very large insert can evict a disproportionate share of the cache's useful working set in one call, since LRU eviction has no concept of "how much value am I giving up" versus "how much space do I need," only recency order. Rejecting any item above a stricter fraction of the total budget (not just above the full budget outright) is a common guardrail to bound how much of the cache one oversized insert can wipe out.
- A common wrong turn: forgetting to subtract an existing key's old size before recomputing whether a
putfits, which either double-counts that key's footprint (causing unnecessary eviction) or under-counts it (lettingused_bytesdrift above the real budget over many updates); the fix above handles this by removing the old entry's byte contribution before running the eviction loop, verified directly by growing keyafrom 40 to 60 bytes and confirmingused_bytesstays correct and within budget afterward.
You store tens of millions of items in an in-memory hash table. Resizing by rehashing everything causes long GC/stop-the-world pauses. Design an incremental or progressive resizing strategy that spreads rehash work across insert and lookup operations to avoid long pauses. Describe algorithms, required invariants, and how to preserve correctness during the transition period.
Sample Answer
Direct answer
A normal resize stops the world: it allocates a new, larger bucket array and walks every existing entry into it before anything else can proceed, which is exactly what produces a long garbage collection (GC, the JVM or runtime's process for reclaiming memory) or stop-the-world pause at tens of millions of entries. Incremental (progressive) resizing instead keeps the old and new tables alive side by side and migrates a small, fixed number of buckets on every subsequent put, get, and remove call, so the cost of the resize is spread as a tiny constant surcharge across many operations instead of one enormous pause on a single operation.
Structured elaboration
Algorithm. When the load factor crosses its threshold, do not rehash immediately. Instead:
- Allocate the new, larger bucket array, but keep the old array around too.
- Track a migration cursor (an index into the old array) starting at 0.
- On every subsequent
put,get, andremove, before doing that call's own work, migrate a fixed small number of old buckets (say 2) into the new array, advancing the cursor. Once the cursor passes the end of the old array, drop it and the migration is complete. - While migration is in progress, new inserts go directly into the new table (never the old one), and lookups check the new table first, falling back to the old table only if the new table does not have the key.
Required invariants during the transition period. Every key that existed before the resize started must be found by exactly one of: already migrated into the new table, or still reachable via a lookup into the old table at its old bucket. A key must never be reachable in both stale and fresh form after being explicitly deleted; a remove during migration has to check and clear the key from whichever table currently holds it, old or new. The migration cursor must advance monotonically and only ever look at each old bucket exactly once, so the total migration work across the whole transition is bounded (no bucket is migrated twice, and no bucket is skipped).
Preserving correctness. The critical property is that at every point during migration, a get for any key that exists must succeed by checking new-then-old, and a get for any key that does not exist must fail on both, and a remove mid-migration must delete the key from whichever table it is actually sitting in so it does not reappear from the other one. The demo below verifies all three directly, with remove actually invoked and confirmed to work while _migrating() still reports True, not just asserted in prose.
Code
class IncrementalHashMap:
MIGRATE_PER_OP = 2
def __init__(self, capacity=4):
self._capacity = capacity
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._old_buckets = None
self._old_capacity = None
self._migrate_index = 0
def _migrating(self):
return self._old_buckets is not None
def _start_resize(self):
self._old_buckets = self._buckets
self._old_capacity = self._capacity
self._capacity *= 2
self._buckets = [[] for _ in range(self._capacity)]
self._migrate_index = 0
def _migrate_step(self):
if not self._migrating():
return
for _ in range(self.MIGRATE_PER_OP):
if self._migrate_index >= self._old_capacity:
self._old_buckets = None
self._old_capacity = None
self._migrate_index = 0
return
bucket = self._old_buckets[self._migrate_index]
for k, v in bucket:
idx = hash(k) % self._capacity
self._buckets[idx].append((k, v))
self._migrate_index += 1
def put(self, key, value):
self._migrate_step()
if not self._migrating() and (self._size + 1) / self._capacity > 0.75:
self._start_resize()
self._migrate_step()
idx = hash(key) % self._capacity
for i, (k, v) in enumerate(self._buckets[idx]):
if k == key:
self._buckets[idx][i] = (key, value)
return
self._buckets[idx].append((key, value))
self._size += 1
def get(self, key):
self._migrate_step()
idx = hash(key) % self._capacity
for k, v in self._buckets[idx]:
if k == key:
return v
if self._migrating():
old_idx = hash(key) % self._old_capacity
for k, v in self._old_buckets[old_idx]:
if k == key:
return v
return None
def remove(self, key):
self._migrate_step()
idx = hash(key) % self._capacity
for i, (k, v) in enumerate(self._buckets[idx]):
if k == key:
del self._buckets[idx][i]
self._size -= 1
return True
if self._migrating():
old_idx = hash(key) % self._old_capacity
for i, (k, v) in enumerate(self._old_buckets[old_idx]):
if k == key:
del self._old_buckets[old_idx][i]
return True
return False
if __name__ == "__main__":
# Bigger starting table + MIGRATE_PER_OP=1 so migration stays in flight
# across several operations, wide enough to test remove() WHILE it's happening.
m = IncrementalHashMap(capacity=8)
m.MIGRATE_PER_OP = 1
for i in range(6):
m.put(f"k{i}", i)
m.put("k6", 6) # crosses load factor 0.75 at capacity 8, starts migration (old_capacity=8)
print("mid-migration right after starting? ->", m._migrating(),
"| old_capacity ->", m._old_capacity, "| new capacity ->", m._capacity,
"| migrate_index ->", m._migrate_index)
# Remove a key WHILE migration is still in flight (only 1 bucket/op migrated,
# 8 old buckets total, so several ops are needed before it finishes).
removed = m.remove("k1")
print("remove k1 while still migrating ->", removed, "| still migrating ->", m._migrating())
print("get k1 after remove ->", m.get("k1"))
# never-inserted key while migration is still in flight
print("get on never-inserted key while migrating ->", m.get("zzz_absent"), "| still migrating ->", m._migrating())
print("remove on never-inserted key while migrating ->", m.remove("zzz_absent"))
print("other keys still correct while migration continues ->",
all(m.get(f"k{i}") == i for i in range(7) if i != 1))
# Force-drain any in-flight migration (including any cascading second resize
# triggered by further puts below) so we can assert a clean post-migration state.
for i in range(7, 20):
m.put(f"k{i}", i)
while m._migrating():
m._migrate_step()
print("migration fully drained ->", not m._migrating())
print("k1 stays removed after migration completes ->", m.get("k1") is None)
print("all surviving keys correct post-migration ->",
all(m.get(f"k{i}") == i for i in range(20) if i != 1))
Output (executed as shown):
mid-migration right after starting? -> True | old_capacity -> 8 | new capacity -> 16 | migrate_index -> 1
remove k1 while still migrating -> True | still migrating -> True
get k1 after remove -> None
get on never-inserted key while migrating -> None | still migrating -> True
remove on never-inserted key while migrating -> False
other keys still correct while migration continues -> True
migration fully drained -> True
k1 stays removed after migration completes -> True
all surviving keys correct post-migration -> True
Trade-offs and pitfalls
- Extra memory during the transition. Both the old and new arrays are alive simultaneously until migration completes, roughly 1.5x the steady-state memory at the moment right after a resize starts (old array plus a new array sized double the old). For a table already holding tens of millions of entries, this transient overhead has to be budgeted for, not just the steady-state size.
- Read amplification while migrating. A lookup for a key that has not yet been migrated costs two bucket scans (new table miss, then old table check) instead of one; this is the price paid for never taking a single big pause, and it is bounded and predictable rather than a spike.
- The migration rate is a tunable knob. Migrating too few buckets per operation (say 1) stretches the transition period over more operations, each cheaper; migrating too many (say the whole table) collapses back into the stop-the-world behavior this design exists to avoid. The right rate is chosen so the transition finishes comfortably before the next resize would otherwise be needed.
- A second resize must not start before the first finishes. The guard here explicitly checks
not self._migrating()before starting a new resize; without it, an old-old-new three-way state becomes possible and the invariant that a key is findable in exactly the old-or-new pair breaks down. - A common wrong turn: treating the migration cursor as optional and instead trying to lazily migrate only the buckets a lookup happens to touch. That approach never provides a bound on how long the tail of untouched old buckets survives, so a resize can, in the worst case, never fully complete if some old buckets are never queried again, quietly doubling memory forever instead of just temporarily.
Explain the concept of load factor in hash tables and how it affects performance and memory usage. Describe the resize (rehash) operation when capacity is doubled and provide an amortized analysis showing that average insertion cost remains O(1). Discuss trade-offs of different resize thresholds (e.g., 0.5 vs 0.75).
Sample Answer
Direct answer
Load factor is the ratio of stored entries to the number of buckets (n / m). A hash table resizes,
allocating a bigger backing array and re-inserting every existing entry, once the load factor crosses
a chosen threshold (commonly 0.75), because letting it climb further makes collisions, and therefore
lookups, get slower.
Structured elaboration
Why load factor matters. For a table using chaining, the average chain length is exactly the
load factor, so a load factor of 0.75 means the average bucket holds 0.75 entries, still effectively
O(1) to scan. Left unchecked (say load factor 20), average chain length would be 20, no longer
meaningfully O(1). For open addressing the effect is sharper: expected probe length grows roughly
like 1 / (1 - load factor), which is fine at 0.5 (about 2 probes) but blows up as load factor
approaches 1 (10 probes at 0.9, effectively unbounded as it approaches 1.0), which is exactly why
open-addressing tables typically resize at a lower threshold than chaining tables do.
What happens during a resize. The table allocates a new backing array, usually double the old
capacity, and re-inserts every live entry by recomputing each one's bucket index against the new
capacity (a key's old bucket index is generally meaningless against a differently-sized table, since
bucket index is hash(key) % new_capacity). This is an O(n) operation, expensive on the one insert
that triggers it, but because it only happens after n has doubled since the last resize, the total
resizing cost summed over n inserts is only O(n), an average (amortized) cost of O(1) extra per
insert (the full amortized-cost proof is worth working through rigorously on its own).
Threshold choice: 0.5 vs 0.75. A lower threshold (0.5) keeps average probe/chain length shorter
at the cost of more frequent resizes and roughly double the wasted (empty) capacity at any given
moment. A higher threshold (0.75, Java HashMap and CPython dict's rough working range) resizes less
often and wastes less memory, at the cost of slightly longer average probes/chains right before a
resize fires. Neither is "correct"; it is a memory-vs-latency trade-off tuned to the expected
workload, latency-sensitive services with memory to spare often pick a lower threshold on purpose.
Worked example
Table starts at capacity 4, threshold 0.75 (resize when entries > 3):
- Insert 1, 2, 3 entries: load factor 0.25, 0.5, 0.75. The 3rd insert leaves load factor exactly at
the threshold; whether that fires a resize depends on whether the check is>or>=capacity*
threshold, an implementation detail worth being precise about in an interview. - Insert the 4th entry: load factor would be 1.0, over threshold, so the table resizes to capacity 8
first, re-inserting all 4 existing entries (now at load factor 0.5 in the new table), then places
the 4th entry.
Trade-offs and pitfalls
A frequent mistake is treating the resize threshold as a fixed universal constant rather than a
tunable trade-off, real systems facing bursty, unpredictable growth sometimes pre-size a table to its
expected final count specifically to avoid paying for resizes during a latency-sensitive burst
(worth working out with real numbers for your expected N). A second pitfall is forgetting that
resizing itself is not free even though it is amortized O(1): a single resize on a very large table
is a real, visible latency spike on whichever operation triggers it, which is exactly the motivation
for incremental/progressive resizing strategies, a design worth exploring in depth on its own, in latency-sensitive
production systems.
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.