Implement a Key-Value Store Without Built-In Maps
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an in-memory key-value map class from scratch without using Python's built-in dict, set, frozenset, or any standard-library mapping or set container built on top of them. Raw fixed-size Python list arrays, equality comparisons (==), and Python's hash() function are permitted.
Your store class must handle hash collisions internally (never raising collision errors to callers), grow dynamically as entries accumulate, and support three operations in O(1) expected / amortized time:
put(key, value) -> None— associatesvaluewithkey, overwriting the previous value if an equal key is already stored.get(key) -> Any— returns the value currently stored forkey, orNoneifkeyis absent.remove(key) -> Any— deleteskeyfrom the map and returns its previously stored value, or returnsNoneifkeywas absent.
Note that None is both a valid key and a valid stored value, so internal empty/deleted slot bookkeeping must not collide with caller data.
For automated testing, implement key_value_store(operations, arguments), which creates one empty store, executes each operation with its corresponding argument list, and returns a list of outputs (None for "put", and the method return value for "get" and "remove").
Examples
Example 1
Input:
operations = ["put", "get", "put", "get", "remove", "get", "remove"]
arguments = [["theme", "light"], ["theme"], ["theme", "dark"], ["theme"], ["theme"], ["theme"], ["theme"]]
Output:
[None, "light", None, "dark", "dark", None, None]
Explanation: "theme" is first stored with "light", then overwritten in place with "dark". The first remove("theme") deletes the entry and returns "dark"; subsequent get and remove calls see that "theme" is gone and return None.
Example 2
Input:
operations = ["put", "put", "get", "get", "remove"]
arguments = [[3, "bronze"], [5, "silver"], [5], [9], [3]]
Output:
[None, None, "silver", None, "bronze"]
Explanation: Keys 3 and 5 are stored under separate entries. get(5) retrieves "silver", get(9) returns None for an unstored key, and remove(3) deletes key 3 and returns "bronze".
Example 3
Input:
operations = ["put", "put", "get", "get", "remove", "get"]
arguments = [[None, 42], ["zero", None], [None], ["zero"], [None], [None]]
Output:
[None, None, 42, None, 42, None]
Explanation: None can be stored as a key (None -> 42) and also as a value ("zero" -> None) without interfering with internal empty-slot or tombstone markers. Removing None returns 42 and leaves later lookups for None returning None.
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every entry in
operationsis"put","get", or"remove" - Keys are hashable Python objects compared via
==; values can be arbitrary Python objects (includingNone) - Built-in
dict,set,frozenset, and library map/set classes are forbidden
Step-by-step walkthrough
Understand the problem and return contract
We need to build a key-value store class from scratch—supporting
put(key, value),get(key), andremove(key)—without using Python's built-indict,set, or any library mapping built on top of them. Our only raw storage is fixed-length Pythonlistarrays.Checking the sample tests pins down the exact return values expected by
key_value_store(operations, arguments):put(key, value)storesvalueunderkey(overwriting any previous value forkey) and returnsNone.get(key)returns the value currently stored underkey, orNoneifkeyis missing. Notice in Example 3 thatNoneitself can be used as both a key and a valid stored value!remove(key)deleteskeyand returns the value that was removed, orNoneifkeywas not present.
Keys are compared by equality (
==), and we may call Python's built-inhash(key)to convert any hashable key into an integer.Turn a key into an array index
A naive store keeps a single list of
[key, value]pairs and scans it from start to finish on every call. That handles any key type with zero collisions, and we use it as a brute-force cross-check in our tests—but scanningnkeys makes every operationO(n).To reach
O(1)expected time, we allocate two parallel fixed-length listsself.keysandself.valuesof sizecapacity(a power of two, starting at8) and compute a key's home slot directly from its hash:- Call
hash(key)to get a signed integer (equal keys such as1and1.0are guaranteed by Python to produce equal hashes). - Scramble the hash with multiplicative Fibonacci hashing: multiply by an odd 64-bit constant near
2^64 / golden_ratio, mask to 64 unsigned bits with_MASK_64, and right-shift to keep the toplog2(capacity)bits.
Why scramble instead of taking
hash(key) % capacity? In Python,hash(k) == kfor small non-negative integers (0, 1, 2, ...). Without scrambling, consecutive integer keys land in one long contiguous block of slots, causing probes that hit the start of the block to walk across all of them. Taking the top bits of the 64-bit product mixes every low input bit upward via multiplication carries.# Odd 64-bit constant near 2^64 / golden_ratio for multiplicative Fibonacci hashing _GOLDEN_RATIO_64 = 0x9E3779B97F4A7C15 _MASK_64 = (1 << 64) - 1def _allocate(self, capacity: int) -> None: # keys[i] holds a live key, _EMPTY, or _DELETED; values[i] holds keys[i]'s value self.keys = [_EMPTY] * capacity self.values = [None] * capacity # Right-shift amount to extract the top log2(capacity) bits of a 64-bit mixed hash index_bits = capacity.bit_length() - 1 self.shift = 64 - index_bits def _home_slot(self, key: Any) -> int: """Compute the initial slot for `key` by scrambling hash(key) and taking top bits.""" # Masking with _MASK_64 converts negative hashes into unsigned 64-bit integers. # Keeping the top bits (>> self.shift) mixes all lower bits upward via carries, # preventing consecutive integers from forming one long contiguous cluster. mixed_hash = (hash(key) * _GOLDEN_RATIO_64) & _MASK_64 return mixed_hash >> self.shift- Call
Handle collisions with linear probing
Even with a great hash mixer, two distinct keys will eventually map to the same home slot—a collision. Raising an exception on a collision breaks the abstraction for callers; the store must resolve collisions internally.
We use open addressing (storing at most one entry directly inside each array slot, with no nested sub-lists) combined with linear probing: if
slotis already occupied by a different key, step forward to(slot + 1) % capacity,(slot + 2) % capacity, and so on, wrapping around the end of the array until we find either our key or a slot that has never been used (_EMPTY):Suppose capacity = 8, and keys A, B, C all have _home_slot == 6: put(A, 10) -> lands at slot 6 put(B, 20) -> slot 6 busy -> lands at slot 7 put(C, 30) -> slot 6 busy -> slot 7 busy -> wraps to slot 0! Slots: [ C | _ | _ | _ | _ | _ | A | B ] Index: 0 1 2 3 4 5 6 7When
get(C)runs later, it starts at home slot6, seesA != C, steps to7(B != C), wraps to0(C == C), and returns30! If we searched for a missing keyDwith home slot6, we would walk6 -> 7 -> 0 -> 1, see_EMPTYat slot1, and know for certainDwas never inserted.Why removals need tombstones
What happens if we now call
remove(B)at slot7in the diagram above? Look at what goes wrong if we naively reset slot7back to_EMPTY:BAD (reset slot 7 to _EMPTY): Slots: [ C | _ | _ | _ | _ | _ | A | _EMPTY ] get(C) starts at 6 (A), steps to 7 (_EMPTY) -> STOPS EARLY and claims C is missing! GOOD (mark slot 7 with a _DELETED tombstone): Slots: [ C | _ | _ | _ | _ | _ | A | _DELETED ] get(C) starts at 6 (A), walks past 7 (_DELETED), wraps to 0 (C) -> finds C!So we need two distinct private sentinel objects,
_EMPTYand_DELETED(a tombstone), compared withisso that no caller key—not evenNone—can ever be confused with a sentinel.Watch out for one subtle trap when inserting after removals: if slot
7is_DELETEDand the caller callsput(C, 99)to updateC, we must not stop at slot7and write a second copy ofCthere! Instead,_probe(key)records the first_DELETEDslot it sees infirst_available, keeps walking all the way until it either findsCat slot0(soputupdates slot0in place) or hits_EMPTYat slot1(confirmingkeyis genuinely new, soputcan safely reusefirst_available).class _Marker: """Private sentinel object so no caller's key (even None) can match a marker.""" def __init__(self, name: str): self.name = name def __repr__(self) -> str: return self.name _EMPTY = _Marker("EMPTY") # slot has never held a key: probes can safely stop here _DELETED = _Marker("DELETED") # tombstone left by remove(): probes must keep walking past itdef _probe(self, key: Any) -> Tuple[int, int]: """Walk `key`'s linear-probing path until finding `key` or reaching `_EMPTY`. Returns `(found_index, insert_index)`: - `found_index`: slot holding an equal key, or -1 if `key` is absent. - `insert_index`: first `_DELETED` tombstone on the path, or the stopping `_EMPTY` slot. """ capacity = len(self.keys) slot = self._home_slot(key) first_available = -1 # Guaranteed to terminate because rebuilds keep at least 1/3 of slots _EMPTY. while self.keys[slot] is not _EMPTY: current_key = self.keys[slot] if current_key is _DELETED: # Remember the first reusable tombstone, but DO NOT stop yet: # `key` may still sit further down the cluster! if first_available == -1: first_available = slot elif current_key == key: return slot, first_available slot = (slot + 1) % capacity if first_available == -1: first_available = slot return -1, first_availableImplement put, get, and remove
With
_probehandling all slot navigation,put,get, andremovebecome short and clear. We track two counters:self.size: how many live keys are currently in the store.self.filled: how many slots are not_EMPTY(live keys plus_DELETEDtombstones).
Why track
self.filledseparately fromself.size? Because probes have to step over tombstones just like live keys! If a caller repeatedly inserts and deletes fresh keys (put(0), remove(0), put(1), remove(1), ...),self.sizestays at0while tombstones fill every slot; if we only checkedself.size, zero_EMPTYslots would remain and_probewould loop forever. Rebuilding wheneverself.filled / capacity >= 2/3(writtenself.filled * 3 >= len(self.keys) * 2in exact integer math) guarantees at least1/3of slots are always_EMPTY.def put(self, key: Any, value: Any) -> None: """Insert or overwrite `key` with `value`.""" found_slot, insert_slot = self._probe(key) if found_slot != -1: self.values[found_slot] = value return # Reusing a _DELETED tombstone keeps `self.filled` unchanged; claiming a fresh # _EMPTY slot increases the number of non-empty slots that probes must walk past. if self.keys[insert_slot] is _EMPTY: self.filled += 1 self.keys[insert_slot] = key self.values[insert_slot] = value self.size += 1 # Rebuild as soon as non-empty slots (live + tombstones) reach 2/3 of capacity # (written with integer multiplication to avoid float rounding). if self.filled * 3 >= len(self.keys) * 2: self._rebuild() def get(self, key: Any) -> Any: """Return the value stored for `key`, or None if `key` is not present.""" found_slot, _ = self._probe(key) if found_slot == -1: return None return self.values[found_slot] def remove(self, key: Any) -> Any: """Delete `key` and return its old value, or None if `key` is not present.""" found_slot, _ = self._probe(key) if found_slot == -1: return None removed_value = self.values[found_slot] # Leave a tombstone instead of _EMPTY so later keys in the same probe chain stay reachable. self.keys[found_slot] = _DELETED self.values[found_slot] = None self.size -= 1 return removed_valueRebuild to grow and sweep away tombstones
When
self.filledhits2/3ofcapacity,_rebuild()allocates clean arrays whosenew_capacityis the smallest power of two>= 8and>= 4 * self.size, then re-inserts only the live keys (discarding all tombstones).Why
>= 4 * self.size? Right after a rebuild, the table is at most1/4full (filled <= 1/4 * new_capacity) with zero tombstones. Before the next rebuild can trigger at2/3 * new_capacity, callers must fill at least(2/3 - 1/4) * new_capacity = (5/12) * new_capacityfresh_EMPTYslots. Charging theO(new_capacity)rebuild work across those>= (5/12) * new_capacityoperations adds onlyO(1)extra work per operation—amortizedO(1)time—whether the rebuild grew the table for more keys or cleaned up a table clogged with tombstones!def _rebuild(self) -> None: """Rehash live entries into a clean power-of-two table at most 1/4 full.""" old_keys = self.keys old_values = self.values # Choose the smallest power-of-two capacity >= MIN_CAPACITY and >= 4 * live size. # Starting <= 1/4 full and rebuilding at 2/3 full guarantees >= 5/12 * capacity # new slot fills before the next rebuild, giving amortized O(1) per operation. new_capacity = self.MIN_CAPACITY while new_capacity < 4 * self.size: new_capacity *= 2 self._allocate(new_capacity) self.filled = self.size # all tombstones are discarded during the copy for old_slot in range(len(old_keys)): key = old_keys[old_slot] if key is _EMPTY or key is _DELETED: continue slot = self._home_slot(key) while self.keys[slot] is not _EMPTY: slot = (slot + 1) % new_capacity self.keys[slot] = key self.values[slot] = old_values[old_slot]Connect the driver and trace Example 2
Finally,
key_value_storeinstantiates oneHashMap, executes each(op, args)pair in order, and collects the return values.def key_value_store(operations: List[str], arguments: List[List]) -> List: store = HashMap() results = [] for op, args in zip(operations, arguments): if op == "put": store.put(args[0], args[1]) results.append(None) elif op == "get": results.append(store.get(args[0])) elif op == "remove": results.append(store.remove(args[0])) else: raise ValueError(f"Unknown operation: {op}") return resultsLet us trace Example 2:
put(3, "bronze"),put(5, "silver"),get(5),get(9),remove(3)with initialcapacity = 8(shift = 61):Start: keys = [_EMPTY] * 8, size = 0, filled = 0 1. put(3, 'bronze'): _home_slot(3) == 6 -> slot 6 is _EMPTY keys[6] = 3, values[6] = 'bronze', size = 1, filled = 1 (1*3 < 8*2) -> appends None 2. put(5, 'silver'): _home_slot(5) == 0 -> slot 0 is _EMPTY keys[0] = 5, values[0] = 'silver', size = 2, filled = 2 (2*3 < 8*2) -> appends None 3. get(5): _probe(5) checks slot 0, sees key 5 == 5 -> appends 'silver' 4. get(9): _probe(9) checks _home_slot(9) == 4, sees _EMPTY -> appends None 5. remove(3): _probe(3) checks slot 6, sees key 3 == 3 keys[6] = _DELETED, values[6] = None, size = 1, filled = 2 -> appends 'bronze' Output: [None, None, 'silver', None, 'bronze']Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class _Marker: """Private sentinel object so no caller's key (even None) can match a marker.""" def __init__(self, name: str): self.name = name def __repr__(self) -> str: return self.name _EMPTY = _Marker("EMPTY") # slot has never held a key: probes can safely stop here _DELETED = _Marker("DELETED") # tombstone left by remove(): probes must keep walking past it # Odd 64-bit constant near 2^64 / golden_ratio for multiplicative Fibonacci hashing _GOLDEN_RATIO_64 = 0x9E3779B97F4A7C15 _MASK_64 = (1 << 64) - 1 class HashMap: """Hash table using open addressing, linear probing, and tombstones over plain lists.""" MIN_CAPACITY = 8 # capacity is always a power of two >= 8 def __init__(self): # size: count of currently live key-value pairs # filled: live keys + _DELETED tombstones (all slots that are not _EMPTY) self.size = 0 self.filled = 0 self._allocate(self.MIN_CAPACITY) def _allocate(self, capacity: int) -> None: # keys[i] holds a live key, _EMPTY, or _DELETED; values[i] holds keys[i]'s value self.keys = [_EMPTY] * capacity self.values = [None] * capacity # Right-shift amount to extract the top log2(capacity) bits of a 64-bit mixed hash index_bits = capacity.bit_length() - 1 self.shift = 64 - index_bits def _home_slot(self, key: Any) -> int: """Compute the initial slot for `key` by scrambling hash(key) and taking top bits.""" # Masking with _MASK_64 converts negative hashes into unsigned 64-bit integers. # Keeping the top bits (>> self.shift) mixes all lower bits upward via carries, # preventing consecutive integers from forming one long contiguous cluster. mixed_hash = (hash(key) * _GOLDEN_RATIO_64) & _MASK_64 return mixed_hash >> self.shift def _probe(self, key: Any) -> Tuple[int, int]: """Walk `key`'s linear-probing path until finding `key` or reaching `_EMPTY`. Returns `(found_index, insert_index)`: - `found_index`: slot holding an equal key, or -1 if `key` is absent. - `insert_index`: first `_DELETED` tombstone on the path, or the stopping `_EMPTY` slot. """ capacity = len(self.keys) slot = self._home_slot(key) first_available = -1 # Guaranteed to terminate because rebuilds keep at least 1/3 of slots _EMPTY. while self.keys[slot] is not _EMPTY: current_key = self.keys[slot] if current_key is _DELETED: # Remember the first reusable tombstone, but DO NOT stop yet: # `key` may still sit further down the cluster! if first_available == -1: first_available = slot elif current_key == key: return slot, first_available slot = (slot + 1) % capacity if first_available == -1: first_available = slot return -1, first_available def put(self, key: Any, value: Any) -> None: """Insert or overwrite `key` with `value`.""" found_slot, insert_slot = self._probe(key) if found_slot != -1: self.values[found_slot] = value return # Reusing a _DELETED tombstone keeps `self.filled` unchanged; claiming a fresh # _EMPTY slot increases the number of non-empty slots that probes must walk past. if self.keys[insert_slot] is _EMPTY: self.filled += 1 self.keys[insert_slot] = key self.values[insert_slot] = value self.size += 1 # Rebuild as soon as non-empty slots (live + tombstones) reach 2/3 of capacity # (written with integer multiplication to avoid float rounding). if self.filled * 3 >= len(self.keys) * 2: self._rebuild() def get(self, key: Any) -> Any: """Return the value stored for `key`, or None if `key` is not present.""" found_slot, _ = self._probe(key) if found_slot == -1: return None return self.values[found_slot] def remove(self, key: Any) -> Any: """Delete `key` and return its old value, or None if `key` is not present.""" found_slot, _ = self._probe(key) if found_slot == -1: return None removed_value = self.values[found_slot] # Leave a tombstone instead of _EMPTY so later keys in the same probe chain stay reachable. self.keys[found_slot] = _DELETED self.values[found_slot] = None self.size -= 1 return removed_value def _rebuild(self) -> None: """Rehash live entries into a clean power-of-two table at most 1/4 full.""" old_keys = self.keys old_values = self.values # Choose the smallest power-of-two capacity >= MIN_CAPACITY and >= 4 * live size. # Starting <= 1/4 full and rebuilding at 2/3 full guarantees >= 5/12 * capacity # new slot fills before the next rebuild, giving amortized O(1) per operation. new_capacity = self.MIN_CAPACITY while new_capacity < 4 * self.size: new_capacity *= 2 self._allocate(new_capacity) self.filled = self.size # all tombstones are discarded during the copy for old_slot in range(len(old_keys)): key = old_keys[old_slot] if key is _EMPTY or key is _DELETED: continue slot = self._home_slot(key) while self.keys[slot] is not _EMPTY: slot = (slot + 1) % new_capacity self.keys[slot] = key self.values[slot] = old_values[old_slot] def key_value_store(operations: List[str], arguments: List[List]) -> List: store = HashMap() results = [] for op, args in zip(operations, arguments): if op == "put": store.put(args[0], args[1]) results.append(None) elif op == "get": results.append(store.get(args[0])) elif op == "remove": results.append(store.remove(args[0])) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of a row of numbered gym lockers (0 through capacity - 1). Instead of writing everyone's name on a clipboard and reading the entire list every time someone asks for their bag, a hash function turns a person's name into a preferred locker number so you can walk straight there. If that locker is already taken by someone else—a collision—you follow a simple rule called linear probing (a form of open addressing, where every item lives directly inside a single array slot rather than a nested sub-list): step one locker to the right, wrapping around from the end back to locker 0, until you find an unused locker. And when someone checks out permanently, you do not make the locker look brand-new; instead you tape a "vacated — keep walking" note called a tombstone (_DELETED) on the door so anyone whose bag was placed further down the row can still walk past it and find their locker.
Why do simpler approaches fall short? Keeping an unsorted list of [key, value] pairs requires scanning up to all n stored items on every put, get, and remove, turning n operations into O(n^2) time. On the other hand, using a fixed array without collision handling fails the moment two keys map to the same index, and deleting an item by resetting its slot to _EMPTY silently severs the search path for colliding keys placed after it.
Walk through a tiny 4-locker example where keys "cat" and "dog" both hash to locker 1:
put("cat", 10)checks locker1, sees_EMPTY, and stores"cat": 10at slot1.put("dog", 20)checks locker1(occupied by"cat"), steps right to locker2(_EMPTY), and stores"dog": 20at slot2.remove("cat")finds"cat"at slot1, replaces it with_DELETED(leaving slot2untouched), and returns10.get("dog")starts at home slot1, sees_DELETED("keep walking!"), steps to slot2, matches"dog", and returns20.
Complexity
Let n be the number of live keys currently in the store, capacity be the current array length, and alpha = filled / capacity be the load factor—the fraction of array slots that are occupied by either live keys or tombstones. Our store enforces alpha < 2/3.
- Expected time per operation: O(1). Assuming simple uniform hashing—the idealized model where each distinct key's home slot behaves like an independent uniform random draw—keeping
alpha < 2/3keeps contiguous clusters short: classical linear-probing analysis shows an average of roughly(1 + 1 / (1 - alpha)) / 2slot checks (~2atalpha = 2/3) for a hit and(1 + 1 / (1 - alpha)^2) / 2(~5atalpha = 2/3) for a miss. - Amortized time per
put: O(1). Amortized time means the average cost per operation over any worst-case sequence of operations, spreading occasional expensive resizes across the cheap operations that paid for them. Rebuilding copiescapacityslots inO(capacity)time and leaves the fresh table at most1/4full (new_capacity >= 4 * size) with zero tombstones; the next rebuild cannot happen untilfilledclimbs from<= 1/4up to2/3ofnew_capacity, which requires at least(5/12) * new_capacitynew slot fills, so the rebuild work averages out to a constant number of steps perput. - Worst-case time per operation: O(n). Two bad things can happen on a single call:
putcan trigger a fullO(n)table rebuild, or allnkeys can hash into one contiguous cluster so_probemust inspect allnkeys. - Space: O(M), where
Mis the peak number of live keys since the last rebuild. Becauseremoveonly writes tombstones without shrinkingself.keys, inserting10,000keys allocates32,768slots, and even after removing all10,000keys those arrays remain at32,768slots until enough futureputcalls pushfilledto2/3and trigger a shrinking rebuild back down to8.
Edge cases
- Missing keys on
getandremove:_probehits an_EMPTYslot and returns-1, so both methods cleanly returnNone. Noneor0stored as a key or value: Because sentinels_EMPTYand_DELETEDare private_Markerinstances tested withis(object identity), storingNoneas a key or value never collides with our internal markers.- Overwriting an existing key:
putchecksfound_slot != -1after scanning past any tombstones, updatingself.values[found_slot]in place without incrementingself.sizeor creating duplicate keys. - Equal keys across numeric types (
1,1.0,True): Python guarantees1 == 1.0 == Trueandhash(1) == hash(1.0) == hash(True), so our store treats them as the same key just likedict. - Real CPython hash collisions (
hash(-1) == hash(-2)): In CPython-1is reserved internally as an error code at the C level, sohash(-1)returns-2, colliding withhash(-2) == -2; linear probing separates them cleanly using==. - Heavy insert/delete churn: Counting tombstones in
self.filledforces a rebuild that sweeps away tombstones wheneverfilledreaches2/3 * capacity, keeping at least1/3of slots_EMPTYso_probecan never enter an infinite loop. float('nan')keys: Because the specification compares keys strictly with==andnan == nanisFalseunder IEEE-754 floating-point rules, anankey will not match itself on a laterget(Python's built-indictchecksa is b or a == bfirst).
Common mistakes
- Setting a deleted slot back to
_EMPTY: Breaks the probe chain for any colliding key placed past that slot, causinggetto falsely returnNoneandputto insert duplicate copies. - Inserting into the first
_DELETEDtombstone immediately: If you stop probing as soon as you see a tombstone duringput(key, val), you miss an existing copy ofkeysitting further down the cluster and corrupt the table with two entries for the same key. - Checking load factor with
self.sizeinstead ofself.filled: Repeatedput+removepairs leaveself.sizesmall while filling 100% of slots with_DELETED, turningwhile self.keys[slot] is not _EMPTY:into an infinite loop. - Using raw
hash(key) % capacitywith integer keys: Small integers hash to themselves in Python, creating a giant contiguous cluster (primary clustering) where misses near the front must scan the whole run. - Claiming unqualified worst-case
O(1)in the interview: Both open addressing and separate chaining areO(1)expected (and amortized across resizes), while their worst-case single-operation cost isO(n).
Alternative approaches
- Separate chaining: Store a small list (bucket) at each of the
capacityarray indices and append colliding[key, value]pairs tobuckets[home_slot]. Deletion simply removes the pair from its bucket list—no tombstones needed—at the cost of extra per-bucket list allocations and pointer chasing. - Open addressing with backward-shift deletion: Instead of leaving
_DELETEDtombstones onremove, walk forward through the contiguous cluster and shift back any entry whose_home_slotlies cyclically at or before the vacated gap. Lookups stay fast without tombstones, thoughremovelogic is trickier to get bug-free under wraparound. - Balanced binary search tree (e.g., Red-Black or AVL tree): Guarantees strict worst-case
O(log n)time perput,get, andremovewith zero hash functions or collisions, but requires keys to support<ordering rather than equality alone.
Follow-up questions
- Suppose an interviewer argues that bucket chaining fails the O(1) requirement; how do you clarify the complexity guarantees and compare them with open addressing? Acknowledge immediately that in the worst case, if all
nkeys hash to the same bucket, separate chaining degrades to scanning ann-element list inO(n)time—and clarify that when engineers say a hash table isO(1), they mean expectedO(1)under uniform hashing and amortizedO(1)across table resizes whenn / capacityis kept bounded. Then be completely transparent that our open-addressing linear-probing store has the exact same asymptotic guarantees: expectedO(1), amortizedO(1)across_rebuild()calls, and worst-caseO(n)when all keys collide into one cluster (plusO(n)on the singleputthat triggers a rebuild). Open addressing improves cache locality and avoids per-slot list objects, not worst-case Big-O. - What happens to throughput if an adversary crafts inputs that all map to the same home index, and how can a hash table mitigate that attack? Every
putandgetwalks the entiren-element cluster, degradingnrequests fromO(n)total time toO(n^2)CPU time—a denial-of-service attack known as hash flooding. The standard defense is keyed cryptographic hashing such as SipHash (a fast hash function parameterized by a secret per-process random 128-bit key, which CPython uses forstrandbytessince Python 3.4 so attackers cannot predict collisions offline). Note that multiplyinghash(key)by a secret seed is not enough if the attacker sends integers whosehash(key)values already collide before our mixer runs (for instance, multiples of CPython's Mersenne prime2^61 - 1), so untrusted inputs should be hashed directly from their raw bytes with a secret key—or else switch Separate Chaining buckets that exceed a small threshold (say 8 entries) into balanced search trees (O(log n)worst case for comparable keys, as Java'sHashMapdoes). - Which hashing schemes guarantee inspecting only O(1) array positions during lookups even in the strict worst case? Use cuckoo hashing—a scheme with two arrays
T1,T2and two independent hash functionsh1,h2that maintains the invariant that every stored keyklives at eitherT1[h1(k)]orT2[h2(k)]and nowhere else, soget(k)inspects at most 2 slots in the strict worst case (O(1)worst-case lookup!). Whenput(k, v)finds both candidate slots occupied, it placeskinT1[h1(k)]and kicks the previous occupant out to its alternate slot inT2, repeating along a chain of displacements; if a cycle occurs (exceedingO(log n)kicks), the table picks fresh random hash seeds and rebuilds (O(1)expected amortizedputwhen total load stays below50%). If the key set is static and known upfront, two-level perfect hashing (Fredman-Komlos-Szemeredi) sizes each bucket's secondary table quadratically (b_i^2) with a collision-free secondary hash, giving worst-caseO(1)getinO(n)total memory. - How would you adapt this data structure so multiple threads can safely read and mutate entries concurrently? Concurrent calls to
put,remove, or_rebuildrace on shared array slots, counters, and array references (even in CPython, where the Global Interpreter Lock (GIL)—an interpreter mutex allowing only one thread to execute Python bytecodes at a time—can switch threads mid-method between_probeand slot assignment, and is optional in free-threaded Python 3.13+). The simplest fix wrapsput,get, andremovein a singlethreading.Lock, serializing all callers. To scale read-heavy workloads, a readers-writer lock allows many concurrentgetcalls whenever noput/removeis mutating the store. To scale concurrent writers as well, use lock striping—partitioning the store intoSindependent sub-tables (for exampleS = 64shards selected by the top 6 bits of the scrambled hash), each with its own lock and independent_rebuild(), so threads operating on different shards run in parallel without blocking a global resize.
Follow-up questions
- Suppose an interviewer argues that bucket chaining fails the O(1) requirement; how do you clarify the complexity guarantees and compare them with open addressing?
- What happens to throughput if an adversary crafts inputs that all map to the same home index, and how can a hash table mitigate that attack?
- Which hashing schemes guarantee inspecting only O(1) array positions during lookups even in the strict worst case?
- How would you adapt this data structure so multiple threads can safely read and mutate entries concurrently?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes