Full answer
Problem
Build a HashTable class with:
put(key, value): insert or overwrite.get(key, default=None): return the value or the default.remove(key): delete and returnTrue, orFalseif absent.len(table): number of keys.
Example: put("asha", 91), put("asha", 95), then get("asha") returns 95 and the size is 1.
Constraints: keys are hashable Python objects; up to about 10^5 operations; do not use dict for storage.
Brute force
Store pairs in one list and scan it on every operation: O(n) per operation, O(n^2) for n inserts.
Optimal approach
- Allocate
capacitybuckets, each an empty list. - Bucket index =
hash(key) % capacity. put: scan that bucket; overwrite if the key exists, otherwise append and increase the size.- When
size > 0.75 x capacity, double the capacity and re-insert every pair into the new buckets (rehash). Indices change because the modulus changes. getandremovescan only one bucket.
Why it works
A good hash spreads keys roughly evenly, so with load factor at most 0.75 each bucket holds less than one item on average and a scan is O(1) expected. Rehashing costs O(n), but doubling makes it rare, so inserts are O(1) amortised (the same argument as a dynamic array).
Alternatives to name
- Open addressing: store entries directly in the array and probe for the next free slot (linear or quadratic probing). Better cache behaviour; deletion needs tombstones. CPython's
dictuses open addressing. - Hash quality: a poor or adversarial hash puts everything in one bucket and every operation becomes O(n). Languages add hash randomisation (Python does this for strings) to resist crafted collisions.
Complexity
put, get, remove: O(1) average, O(n) worst case. Rehash: O(n), amortised O(1) per insert. Space O(n + capacity).
Code
class HashTable:
"""Hash map with separate chaining and resizing at load factor 0.75."""
def __init__(self, capacity=8):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
def _bucket(self, key):
return self._buckets[hash(key) % len(self._buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value) # update existing key
return
bucket.append((key, value))
self._size += 1
if self._size > 0.75 * len(self._buckets):
self._rehash(2 * len(self._buckets))
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
def remove(self, key):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket.pop(i)
self._size -= 1
return True
return False
def _rehash(self, new_capacity):
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[hash(k) % new_capacity].append((k, v))
def __len__(self):
return self._size
if __name__ == "__main__":
t = HashTable()
t.put("asha", 91)
t.put("ravi", 78)
t.put("asha", 95) # overwrite
assert t.get("asha") == 95 and t.get("ravi") == 78 and len(t) == 2
assert t.get("missing") is None and t.get("missing", 0) == 0
assert t.remove("ravi") is True and t.remove("ravi") is False and len(t) == 1
for i in range(1000): # forces several resizes
t.put(i, i * i)
assert all(t.get(i) == i * i for i in range(1000)) and len(t) == 1001
print("all tests passed")Save as a04_hash_table.py and run python3 a04_hash_table.py. It prints all tests passed (Python 3.13.5).
Edge cases
Overwriting an existing key must not increase the size. Removing a missing key. Keys that hash to the same bucket (integers that differ by a multiple of the capacity). None as a value (the default argument distinguishes "missing" only if you choose a sentinel; the tests use a different default to show this).
Pattern
Hashing with chaining and load-factor-driven resizing. The amortised argument is the same as for dynamic arrays.
class HashTable:
"""Hash map with separate chaining and resizing at load factor 0.75."""
def __init__(self, capacity=8):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
def _bucket(self, key):
return self._buckets[hash(key) % len(self._buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value) # update existing key
return
bucket.append((key, value))
self._size += 1
if self._size > 0.75 * len(self._buckets):
self._rehash(2 * len(self._buckets))
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
def remove(self, key):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket.pop(i)
self._size -= 1
return True
return False
def _rehash(self, new_capacity):
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[hash(k) % new_capacity].append((k, v))
def __len__(self):
return self._size
if __name__ == "__main__":
t = HashTable()
t.put("asha", 91)
t.put("ravi", 78)
t.put("asha", 95) # overwrite
assert t.get("asha") == 95 and t.get("ravi") == 78 and len(t) == 2
assert t.get("missing") is None and t.get("missing", 0) == 0
assert t.remove("ravi") is True and t.remove("ravi") is False and len(t) == 1
for i in range(1000): # forces several resizes
t.put(i, i * i)
assert all(t.get(i) == i * i for i in range(1000)) and len(t) == 1001
print("all tests passed")Separate chaining with lists, doubling at load factor 0.75. The test inserts 1,000 keys to force several rehashes.
Complexity
Time: put/get/remove O(1) average, O(n) worst case; rehash O(n), amortised O(1) per insert. Space: O(n + capacity). Worst case occurs when many keys collide into one bucket, for example with a poor or adversarial hash function.
By level
Fresher: Implements buckets with lists and explains collisions with a small example. States average O(1) operations. Should know that keys must be hashable and why lists cannot be keys.
Mid: Adds load-factor resizing, explains amortised cost and compares chaining with open addressing. Can describe what happens to performance when many keys collide.
Senior: Discusses hash flooding attacks and randomisation, cache locality, tombstones, concurrent hash maps and memory overhead per entry. Can explain why dictionary iteration order in Python 3.7 and later follows insertion order.
Key points
- Bucket = hash(key) mod capacity
- Chaining stores colliding pairs in the same bucket
- Keep load factor below a threshold by doubling and rehashing
- Average O(1), worst case O(n) when keys collide
- Open addressing is the main alternative
Common mistakes
- Forgetting that indices change after resizing
- Increasing size when overwriting an existing key
- Using mutable objects such as lists as keys
- Claiming worst-case O(1)
Follow-ups
- How does open addressing handle deletion?
- Why do languages randomise string hashing?
- How would you make the table thread-safe?
Tips
- Draw buckets with one collision
- Explain load factor with a number
- Mention what Python's dict actually does
Evaluation rubric
- Correct put/get/remove with overwrite semantics
- Resizing with rehash
- Correct average and worst-case analysis
- Knows open addressing and hash quality issues