Hash Table Internals: Collisions, Resizing, and Concurrency
System DesignModel answerLast updated
Explain how an in-memory hash table works under the hood, covering collision strategies, resizing cost, deletion semantics, worst-case behavior, and thread safety.
Hash Table Internals
Most developers use hash maps every day, but interviews often probe whether you understand what is actually happening beneath the API.
Walk through the internal mechanics of a general-purpose in-memory hash table — the kind you would find in a standard library like Java's HashMap or Python's dict — and address each of the following areas:
1. Handling collisions What happens when two keys map to the same bucket? Describe at least two strategies and explain when you would prefer one over the other.
2. Load factor and resizing What is the load factor, why does it matter, and how does geometric resizing keep the amortized insert cost at O(1)?
3. Deleting entries Why is deletion non-trivial in open-addressing schemes, and what are the common solutions?
4. Worst-case behavior When does a hash table degrade to O(n) per operation? What causes it, and how do real implementations guard against it?
5. Iteration order Is the order in which you iterate a hash map defined? What can cause it to change?
6. Thread safety What goes wrong when multiple threads share a hash map without coordination? What are the main approaches to making one safe for concurrent use, and what are their trade-offs?
You do not need to implement the data structure. A clear, structured explanation with reasoning, concrete examples, and trade-offs is expected.
Hints
Hint 1
Start with the fundamental contract: if two keys are equal, their hash codes must also be equal. Everything else follows from how you deal with the cases where unequal keys land in the same bucket.
Hint 2
For the resizing cost, think about how much total copying work happens across all n inserts if the table doubles each time — the sum forms a geometric series.
Hint 3
In open addressing, think carefully about what a lookup does when it hits an empty slot during a probe sequence, and why a naive delete breaks that assumption.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
How a Hash Table Works — and Where It Gets Complicated
The core mechanism
A hash table maps keys to array indices. Given a key, you compute a hash code and reduce it to an index — either hash % capacity or, for power-of-two tables, hash & (capacity - 1). The value lands in that bucket.
The critical contract: equal keys must produce equal hash codes. If that is violated — for example, because a key object is mutated after insertion — the entry becomes unreachable. A related trap is NaN, which is not equal to itself; you can insert it repeatedly and never retrieve it.
Collision handling
Two different keys can hash to the same bucket. The two mainstream strategies are:
Separate chaining — each bucket holds a list (or tree) of entries. Java's HashMap and C++'s std::unordered_map both use this. Deletions are straightforward, and the table can exceed load factor 1. The downside is poor cache locality and a heap allocation per node. Java 8+ converts a bucket to a red-black tree once it holds eight or more entries, capping worst-case per-bucket cost at O(log n) instead of O(n).
Open addressing — all entries live directly in the array. On a collision, you probe alternate slots: linear probing (i+1, i+2, …), quadratic probing, or double hashing. Linear probing is the most cache-friendly but suffers from primary clustering — long runs of occupied slots that grow and merge. Robin Hood hashing partially corrects this by letting entries that are far from their home slot displace entries that are close. Python's dict and Google's SwissTable are open-addressing implementations.
The choice is mostly about cache behavior vs. memory overhead and deletion complexity. Open addressing is typically faster in practice at low load factors; chaining is more forgiving at high ones.
Load factor and resizing
The load factor α = entries / capacity determines expected probe length. For chaining it is roughly 1 + α; for linear probing it grows much sharper as α approaches 1. Typical thresholds: Java uses 0.75, Python approximately 2/3, C++'s unordered_map defaults to 1.0.
When the threshold is crossed, the table allocates a new array — usually 2× the current capacity — and reinserts every entry. Because indices depend on capacity, entries cannot simply be copied; every key must be rehashed. That single resize costs O(n), but with geometric growth the total copying across n inserts is n + n/2 + n/4 + … < 2n, giving amortized O(1) per insert. Growing by a fixed amount instead (say, +100 slots) makes total copying O(n²).
If the table also shrinks, use hysteresis — for instance, grow at 0.75 and shrink at 0.25. Shrinking at 0.5 causes thrashing if inserts and deletes alternate near the threshold. Latency-sensitive systems (Redis, for example) avoid the single large spike by doing incremental rehashing: keep both the old and new arrays in parallel and migrate a small number of buckets on each operation.
Deletion in open addressing
You cannot simply clear a slot. A later key may have probed past it and now sits further down the array. If you empty the slot, a subsequent lookup stops there and incorrectly concludes the key does not exist.
Two standard fixes:
- Tombstones — mark deleted slots with a sentinel. Lookups skip tombstones; inserts can reuse them. The catch: tombstones count toward probe-length calculations, so a delete-heavy workload gradually fills the table with tombstones even as live occupancy stays low. A periodic rehash clears them.
- Backward-shift deletion — after removing a slot, shift subsequent entries in the same cluster back toward their home positions until you hit an empty slot or an entry already at home. No tombstones needed, but each delete does more work.
Worst-case behavior and hash flooding
If every key lands in the same bucket, all operations degrade to O(n), and n inserts cost O(n²). This happens with weak hash functions or adversarially crafted input. Web frameworks were successfully attacked by sending HTTP requests with query parameters designed to collide, saturating server CPU with hash table operations.
Mitigations in practice:
- Bit mixing before indexing. Java XORs the high 16 bits of the hash code into the low 16 bits to prevent a bad key distribution from concentrating in a few buckets.
- Randomized hashes with a per-process secret. Python randomizes
strhashing at startup using SipHash with a random seed, so an attacker cannot precompute collisions across runs. - Treeification (Java 8+) bounds per-bucket cost at O(log n) even in the presence of collisions.
- Rate-limiting or capping the number of untrusted keys processed.
Iteration order
Iterating a hash table walks the bucket array in index order, so the sequence depends on hash values, current capacity, and resize history. Order can change after a resize and can differ between process restarts when hashes are seeded. Never rely on it for correctness.
If order matters: LinkedHashMap in Java and Python 3.7+ dict preserve insertion order. A sorted map (TreeMap, std::map) maintains key order at the cost of O(log n) operations. Mutating a map while iterating it is undefined behavior in C++ (rehashing invalidates iterators) and raises ConcurrentModificationException in Java via a modification counter.
Concurrency
A plain hash table is not thread-safe even for one writer and multiple readers. Failure modes include: lost updates from concurrent writes, a reader seeing a partially constructed entry mid-resize, and — in Java 7 — a cycle in a bucket's linked list caused by a concurrent rehash, causing an infinite loop on the next get.
Options from coarse to fine:
- Global lock — wrap every operation in a mutex. Correct and simple, but all threads serialize. A reader-writer lock improves read-heavy workloads.
- Lock striping — divide buckets into segments, each with its own lock. Java 7's
ConcurrentHashMapused 16 segments. Java 8+ refined this: CAS for inserting into empty buckets, a per-bucket lock for chains, lock-free volatile reads everywhere, and a cooperative resize across threads. Size is tracked with striped counters to avoid contention on a single field. - Compound operations must be explicit. Two individually safe calls like
containsKey+putare not atomic together; useputIfAbsentorcomputeIfAbsent. - Copy-on-write — any write produces a new map; readers always see a snapshot. Suitable for read-mostly data with infrequent updates.
Complexity summary
| Operation | Average | Worst case |
|---|---|---|
| get / delete | O(1) | O(n); O(log n) with treeification |
| put | O(1) amortized | O(n) on resize |
| iteration | O(capacity + n) | O(capacity + n) |
| space | O(n) | O(n) |
Easy things to miss
- Updating an existing key must not increment the entry count or trigger a resize.
nullkeys: JavaHashMapallows one;ConcurrentHashMapandHashtableforbid them entirely.- A delete-heavy workload can require a rehash even when live occupancy has not grown, purely to purge tombstones.
- Worst-case behavior is often not random — it can be deliberately induced by an attacker, making keyed/randomized hashing a security concern, not just a performance one.