Different keys, same doorway.
Handle collisions instead of assuming a hash uniquely identifies a key.
01 Model the idea
A hash maps a key into a bounded set of bucket positions. Different keys can land in the same bucket, so equality must still be checked. Separate chaining stores a collection of entries in each bucket. The load factor describes the number of entries relative to buckets; controlling it keeps expected chain lengths manageable under suitable hashing assumptions.
Every entry is in its key’s bucket, and each logical key appears once.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
HASH the key to a bucket
SEARCH that bucket for equal key
UPDATE a match or append a new entry03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class ChainedMap:
def __init__(self, capacity=5): self.buckets = [[] for _ in range(capacity)]
def index(self, key): return sum(map(ord, key)) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self.index(key)]
for i, (stored, _) in enumerate(bucket):
if stored == key: bucket[i] = (key, value); return
bucket.append((key, value))
def get(self, key):
for stored, value in self.buckets[self.index(key)]:
if stored == key: return value
raise KeyError(key)
table = ChainedMap()
table.put("ab", 1); table.put("ba", 2); table.put("ab", 3)
print(table.get("ab"), table.get("ba"))3 2
- 1
ab and ba collide under this deliberately simple character-sum hash. Distinct equality checks keep their values independent.
- 2
Updating an existing key replaces its value rather than adding another logical key. A collision is normal and is not itself an error.
- 3
Real maps need suitable hash functions, resizing, and a key contract consistent with equality. This educational hash is not a secure or robust production hash function.
04 Count the cost
Expected O(1) lookup with controlled load; O(n) worst case
O(n + m) entries and m buckets
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Show that two different strings collide under a small character-sum hash without being equal.
Reveal one possible solution +
def bucket(key): return sum(map(ord, key)) % 5
print(bucket("ab") == bucket("ba"))
print("ab" == "ba")06 Check your reasoning
What must be checked after keys land in the same bucket?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.