💡 Summary: What Happens When Two Keys Land in the Same Bucket?
A hash table gives fast average-case lookups by converting a key into a bucket index with a hash function. Because many possible keys map into a limited number of slots, two different keys can easily produce the same index—a situation called a collision.
Instead of overwriting existing data, collision resolution gives clear rules for storing and finding colliding keys. Separate Chaining keeps multiple items in a list/chain at that bucket, while Open Addressing (Linear Probing, Quadratic Probing, and Double Hashing) searches for another open slot inside the table itself.
m slots holding n items. Its load factor is α = n / m. When α rises, collisions become more common, so choosing the right collision rule and resizing early matters:
- Separate Chaining: Bucket
h(k)stores a chain (list/linked list) of entries. Works smoothly even whenα > 1. - Open Addressing: Every item lives directly in the array. If
h(k)is occupied, probing checks alternative indices until an empty slot is found.
| Technique | Probe / Bucket Rule | Key Strength | Watch Out For |
|---|---|---|---|
| Separate Chaining | Chain/list at k % m |
Simple deletion & handles α > 1 |
Extra node/list allocations |
| Linear Probing | (h(k) + i) % m |
Good cache locality in an array | Primary clustering (long busy runs) |
| Quadratic Probing | (h(k) + i²) % m |
Reduces primary clustering | Secondary clustering & probe limits |
| Double Hashing | (h1(k) + i · h2(k)) % m |
Spreads probes well across table | Needs a well-chosen second hash h2(k) |
class ChainedHashTable:
def __init__(self, size=7):
self.size = size
self.buckets = [[] for _ in range(size)]
def _hash(self, key):
return key % self.size
def insert(self, key, value):
idx = self._hash(key)
for item in self.buckets[idx]:
if item[0] == key:
item[1] = value
return idx
self.buckets[idx].append([key, value])
return idx
def get(self, key):
idx = self._hash(key)
for k, v in self.buckets[idx]:
if k == key:
return v
return None
class LinearProbeHashTable:
def __init__(self, size=7):
self.size = size
self.table = [None] * size
self.TOMBSTONE = object()
def _hash(self, key):
return key % self.size
def insert(self, key, value):
start = self._hash(key)
for step in range(self.size):
idx = (start + step) % self.size
slot = self.table[idx]
if slot is None or slot is self.TOMBSTONE or slot[0] == key:
self.table[idx] = (key, value)
return idx, step
raise OverflowError("Hash table is full")
cht = ChainedHashTable(size=7)
for student_id, grade in [(101, "A"), (108, "B+"), (115, "A-"), (104, "O")]:
cht.insert(student_id, grade)
print("Chained lookup 115:", cht.get(115))
print("Bucket [3] chain :", cht.buckets[3])
lht = LinearProbeHashTable(size=7)
for student_id, grade in [(101, "A"), (108, "B+"), (115, "A-")]:
placed, probes = lht.insert(student_id, grade)
print(f"Linear probe inserted {student_id} at slot {placed} (probes={probes})")
m = 7 using h(k) = k % 7. Watch which slots are probed (amber) and where the key lands (green):
- 1. Short-Link & URL Lookup Tables: When short codes or hashed IDs collide in a lookup map, chaining or probing ensures every redirect still resolves to its exact destination.
- 2. Campus Wi-Fi & Router DHCP/Session Tables: Multiple connected devices hashing to the same bucket can be stored cleanly in a bucket chain or probed slot.
- 3. Parking Lot Slot Assignment (Linear Probing): If your assigned bay
#4is occupied, checking#5, then#6models linear probing step-by-step. - 4. Shopping Cart & Inventory Counters: Product SKUs hashed into an in-memory map use collision handling so two distinct SKUs never overwrite each other's stock count.
- 5. Spell-Check & Dictionary Word Buckets: Words sharing a hash bucket are kept in a small chain so lookups only compare against words in that specific bucket.
# 4. Real-Time Inventory SKU Map with Separate Chaining
class InventoryMap:
def __init__(self, capacity=8):
self.capacity = capacity
self.table = [[] for _ in range(capacity)]
def _bucket(self, sku):
total = sum(ord(ch) * (idx + 1) for idx, ch in enumerate(sku))
return total % self.capacity
def add_stock(self, sku, qty):
idx = self._bucket(sku)
for entry in self.table[idx]:
if entry[0] == sku:
entry[1] += qty
return idx, entry[1]
self.table[idx].append([sku, qty])
return idx, qty
inv = InventoryMap(capacity=8)
for sku, qty in [("PEN-101", 25), ("NOTE-204", 15), ("INK-309", 40), ("PEN-101", 10)]:
b_idx, total_qty = inv.add_stock(sku, qty)
print(f"SKU {sku:9s} -> Bucket [{b_idx}], Stock = {total_qty}")
- 6. Web Cache & API Response Memoization: Cached query keys that collide must still return the matching cached payload without cross-talk between users.
- 7. Event Ticket & Seat Reservation Buckets: Booking references hashed into slots find open positions without dropping earlier reservations.
- 8. Log Deduplication & Alert Grouping: Repeated error signatures land in the same bucket so monitoring tools can count occurrences accurately.
- 9. Game Entity & Tile State Grids: Spatial or entity IDs mapped into fixed-size tables use probing or chains when multiple entities overlap a hash cell.
- 10. Deleting Entries Safely in Open Addressing: In linear or quadratic probing, deleting a middle item uses a
TOMBSTONEmarker so later probed keys can still be found during search.
# 10. Tombstone Deletion in Linear Probing so Probe Chains Stay Reachable
EMPTY = None
TOMBSTONE = "DELETED"
class ProbeTable:
def __init__(self, size=7):
self.size = size
self.keys = [EMPTY] * size
def insert(self, key):
start = key % self.size
first_tombstone = None
for i in range(self.size):
idx = (start + i) % self.size
if self.keys[idx] == key:
return idx
if self.keys[idx] == TOMBSTONE and first_tombstone is None:
first_tombstone = idx
elif self.keys[idx] == EMPTY:
target = first_tombstone if first_tombstone is not None else idx
self.keys[target] = key
return target
if first_tombstone is not None:
self.keys[first_tombstone] = key
return first_tombstone
return -1
def delete(self, key):
start = key % self.size
for i in range(self.size):
idx = (start + i) % self.size
if self.keys[idx] == EMPTY:
return False
if self.keys[idx] == key:
self.keys[idx] = TOMBSTONE
return True
return False
def search(self, key):
start = key % self.size
for i in range(self.size):
idx = (start + i) % self.size
if self.keys[idx] == EMPTY:
return -1
if self.keys[idx] == key:
return idx
return -1
pt = ProbeTable(size=7)
for k in [10, 17, 24]:
pt.insert(k)
pt.delete(17) # Leaves TOMBSTONE at index 4 so 24 (at index 5) is still reachable
print("Slots after deleting 17:", pt.keys)
print("Search 24 index :", pt.search(24))
- Collisions are expected: A collision means two keys mapped to the same initial index—it does not mean the hash table is broken.
- Never set a slot to
Nonewhen deleting in open addressing: Setting a slot toNonecan break searches for keys placed further along the probe sequence; use a tombstone/deleted marker or shift properly. - Resize as load factor grows: Resizing into a larger table (often a prime size or power-of-two depending on design) and rehashing keeps average operations fast.
takeaways = [
"Separate Chaining: Stores multiple items per bucket; simple deletion.",
"Linear Probing: Checks next slots (+1, +2, ...); fast cache access, watch for clustering.",
"Quadratic & Double Hashing: Vary jump distances to reduce clustering."
]
for line in takeaways:
print("*", line)