How Hash Tables Handle Collisions, Deletes, and Growth
Data Structure DesignModel answerLast updated
Walk through hash table internals: index mapping, chaining versus linear probing, safe deletion, load-factor resizing, and when operations degrade from O(1) to O(n).
Imagine you are asked to explain, from first principles, how a hash table is built and why its operations are usually constant time. Your explanation should compare two designs: separate chaining and open addressing with linear probing.
Cover the following areas.
-
From key to slot. Describe how an arbitrary key becomes an array position. Include the modulo form and the bitmask form used when the capacity is a power of two. Explain why a table needs both a hashing routine and an equality check.
-
Handling collisions.
- How chaining organizes the entries that share a bucket (lists, arrays, balanced trees).
- How linear probing finds another slot, and why quadratic probing and double hashing exist.
-
Removing entries. Compare deletion in the two designs. Explain why blanking a slot is unsafe under linear probing, and describe two ways to fix it: tombstones and backward-shift deletion.
-
Load factor and growth. Define the load factor, give typical resize thresholds for each design, justify why open addressing needs a lower one, and describe how a resize works. Explain why entries must be re-hashed rather than copied to their old positions.
-
Cost analysis. Give average and worst-case time for insert, search and delete in both designs, plus space usage. Name realistic situations that produce the worst case, and compare the CPU cache behaviour of the two approaches.
A strong answer is structured, gives concrete numbers where they help, and points out common pitfalls.
Hints
Hint 1
Separate the problem into two steps: hash code generation, then compression to an index. Think about what information is lost when only the low bits are kept, and what the equality check resolves that the hash cannot.
Hint 2
For deletion under linear probing, ask what a lookup treats as proof that a key is absent. Then work out what happens to a key that was pushed past a slot that later gets emptied.
Hint 3
For load factor, compare the expected number of probes for linear probing as alpha approaches 1 with the expected chain length 1 + alpha. For resizing, ask what changes in the formula when the capacity changes, and use geometric growth to argue amortized cost.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Key to bucket
Mapping happens in two steps.
- Hash:
h = hash(key)produces an integer. It must be deterministic, and equal keys must give equal hashes. - Compress:
index = h % m. Ifmis a power of two,h & (m - 1)is equivalent and avoids a division. Masking keeps only the low bits, so good implementations first mix in the high bits (Java'sHashMapusesh ^ (h >>> 16)).
Why both hash and equality? Hashing is many-to-one: distinct keys can share a hash, and many hashes land in one bucket after compression. The hash narrows the search to a few candidates; equality picks the correct one. The contract is one-directional: a == b implies hash(a) == hash(b). Break it and an inserted key becomes unfindable.
2. Collision resolution
Separate chaining. Each bucket holds a small collection: a linked list, a dynamic array, or a tree. Java 8+ converts a bin to a red-black tree when it reaches 8 entries and capacity is at least 64, which caps the worst-case bin lookup at O(log n). The load factor may exceed 1 and performance degrades smoothly.
Open addressing. Every entry lives in the array itself, and a collision triggers a deterministic probe sequence.
- Linear probing:
(h + i) % m. Very cache friendly, but it suffers primary clustering: occupied runs merge and grow. - Quadratic probing:
(h + c1·i + c2·i²) % m. Breaks up primary clusters, though keys with the same start still share a path (secondary clustering). - Double hashing:
(h1 + i·h2) % m. Each key has its own step.h2must be nonzero and coprime withmso the sequence visits every slot.
3. Deletion
- Chaining: unlink the entry from its bucket. Nothing else is affected.
- Linear probing: setting
slot[i] = Noneis wrong. A lookup stops at the first empty slot, interpreting it as "the key was never placed beyond here". Example:AandKboth hash to slot 3;Aoccupies 3 andKwas pushed to 4. Empty slot 3 and a lookup forKsees an empty slot immediately and reports "missing".
Fixes:
- Tombstones. Mark the slot
DELETED.- Lookups skip it and continue probing.
- Inserts may reuse the first tombstone seen, but only after confirming the key is not later in the sequence.
- Tombstones lengthen probes, so they must count toward the resize threshold; otherwise the table can fill with tombstones and no empty slot remains to end an unsuccessful search.
- Backward-shift deletion. After emptying the slot, scan forward through the run and move each entry back into the hole if the hole lies on its probe path. No tombstones are created and probe lengths stay short. It works cleanly for linear probing only.
4. Load factor and resizing
alpha = n / m, with n stored keys and capacity m.
Typical thresholds: about 0.75 for chaining (Java default), and 0.5 to 0.7 for open addressing.
The reason for the gap is that linear probing cost explodes near full (Knuth's estimates):
- Successful search: about
0.5 * (1 + 1/(1 - alpha)) - Unsuccessful search: about
0.5 * (1 + 1/(1 - alpha)^2)
At alpha = 0.5 an unsuccessful search takes about 2.5 probes; at 0.9 it is about 50; at 1 the table cannot accept inserts. Chaining's expected cost is just 1 + alpha.
Resize steps:
- Allocate a new array, typically
2m. - Re-insert every live entry at
hash(key) % new_m. - Discard tombstones.
Entries cannot be copied to the same index because the modulus changed: h % m generally differs from h % 2m. In open addressing, stale positions would also corrupt probe sequences. Because capacity grows geometrically, the total rehash work across n inserts is O(n), so insert is amortized O(1), though a single insert that triggers a resize costs O(n).
5. Complexity
| Operation | Chaining avg | Chaining worst | Linear probing avg | Linear probing worst |
|---|---|---|---|---|
| Search | O(1 + alpha) | O(n), or O(log n) with treeified bins | O(1) for bounded alpha < 1 | O(n) |
| Insert | O(1) amortized | O(n) | O(1) amortized | O(n) |
| Delete | O(1 + alpha) | O(n) | O(1) | O(n) |
| Space | O(n + m) plus per-node pointers | O(m), inline |
Worst-case triggers:
- A degenerate hash (constant, or based on low bits that are always equal).
- Power-of-two masking without bit mixing when keys share low bits.
- Hash flooding: an attacker supplies many colliding keys (for example crafted request parameters), so
ninserts cost O(n^2). Mitigations: randomized/seeded hashes (SipHash), tree bins, and limits on input size. - For open addressing: heavy clustering at high alpha, or a table clogged with tombstones.
Cache locality. Chaining follows pointers to scattered heap nodes, so each hop can miss the cache. Linear probing scans contiguous memory: one 64-byte line holds several slots and the prefetcher helps. This is why modern high-performance tables (SwissTable, F14, hashbrown) use open addressing despite its sensitivity to load.
Edge cases and pitfalls
- Equal keys with unequal hashes: lookups silently fail.
- Mutating a key after insertion: the entry sits in the wrong bucket.
- Many deletes then inserts: tombstone buildup; rehash at the same capacity when live count is low.
- Using
Noneas a key: use private sentinel objects for EMPTY and DELETED soNoneremains valid. NaNkeys:nan != nan; checking identity before equality keeps the same object findable.- Forgetting to count tombstones toward load, leading to infinite probe loops.
Sketch: linear probing with tombstones (Python)
_EMPTY = object()
_DELETED = object()
class ProbingMap:
def __init__(self, cap=8, max_load=0.6):
c = 1
while c < cap:
c <<= 1
self.keys = [_EMPTY] * c
self.vals = [None] * c
self.size = 0 # live entries
self.used = 0 # live + tombstones
self.max_load = max_load
def _probe(self, key):
mask = len(self.keys) - 1
i = hash(key) & mask
first_free = None
while True:
k = self.keys[i]
if k is _EMPTY:
return None, (i if first_free is None else first_free)
if k is _DELETED:
if first_free is None:
first_free = i
elif k is key or k == key:
return i, first_free
i = (i + 1) & mask
def get(self, key, default=None):
i, _ = self._probe(key)
return default if i is None else self.vals[i]
def put(self, key, val):
i, free = self._probe(key)
if i is not None:
self.vals[i] = val
return
if self.keys[free] is _EMPTY:
self.used += 1
self.keys[free], self.vals[free] = key, val
self.size += 1
if self.used / len(self.keys) > self.max_load:
self._resize()
def delete(self, key):
i, _ = self._probe(key)
if i is None:
return False
self.keys[i], self.vals[i] = _DELETED, None
self.size -= 1
return True
def _resize(self):
old_k, old_v = self.keys, self.vals
new_cap = len(old_k) * 2 if self.size / len(old_k) > self.max_load / 2 else len(old_k)
self.keys = [_EMPTY] * new_cap
self.vals = [None] * new_cap
self.size = self.used = 0
for k, v in zip(old_k, old_v):
if k is not _EMPTY and k is not _DELETED:
self.put(k, v)
Because used (live plus tombstones) stays below max_load, at least one _EMPTY slot always exists, so every probe loop terminates.