Two keys share a bucket. How does a hash map cope?
Question
A shop keeps prices in a hash map with 5 buckets. A key goes to bucket hash(key) % 5, and for a small positive int, hash(k) is k. You store product ids 3, 8 and 13 with prices 40, 15 and 99. Then you change the price of 8 to 17.
- All three ids land in bucket 3. How does the map still return the right price for each?
- What happens when you look up 18? It also lands in bucket 3, but it was never stored.
- Python's
dictdoesn't keep a list per bucket. What does it do instead?
Show hints (3)
- "BUCKET IS NOT KEY"
The bucket only tells you where to look. Inside it, keep each key with its value, and compare keys with
==. - "UPDATE OR ADD"
Before you add a pair, walk the bucket. If an equal key is already there, replace its value instead.
- "NO LISTS AT ALL"
Another design uses one flat array. If slot 3 is taken, try other slots in a fixed order until you find a free one. A lookup follows the same order.
Show checked explanation
Each bucket keeps a list of key-value pairs: the hash picks the bucket, and == picks the pair. This is chaining. CPython's dict uses open addressing instead: one array of slots, and a collision tries other slots in a fixed order. Both stay fast only while the table isn't too full.
buckets = [[] for _ in range(5)] def put(key, value): chain = buckets[hash(key) % len(buckets)] for pair in chain: if pair[0] == key: pair[1] = value # same key: replace, don't add return chain.append([key, value]) def get(key, default=None): chain = buckets[hash(key) % len(buckets)] return next((v for k, v in chain if k == key), default) for product, price in [(3, 40), (8, 15), (13, 99), (8, 17)]: put(product, price) print(buckets[3], get(8), get(18))
[[3, 40], [8, 17], [13, 99]] 17 None
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
get(8) walks bucket 3, skips 3 because 3 == 8 is false, and returns 17. get(18) checks all three pairs, finds no equal key and returns None. No other bucket can hold 18, because an equal key would have the same hash.
This design is chaining. The other main design is open addressing: one array, one pair per slot. On a collision you probe, that is, try other slots. The simplest probe takes the next slot and wraps round at the end. With 5 slots:
| key | slots tried | stored in |
|---|---|---|
| 3 | 3 | 3 |
| 8 | 3, 4 | 4 |
| 13 | 3, 4, 0 | 0 |
A lookup for 13 follows the same path: 3, 4, then 0. A lookup for 18 tries 3, 4 and 0, then stops at slot 1, the first empty one.
Deleting needs care. If you delete 8 by emptying slot 4, a lookup for 13 stops at that hole and misses. So the slot gets a "deleted" marker instead. Lookups step over it, and an insert can reuse it.
CPython's dict uses open addressing, as Objects/dictobject.c explains. Its probe isn't simply the next slot: it mixes in higher bits of the hash, so similar hashes spread out.
Both designs depend on the load factor: keys divided by buckets or slots. When it gets high, chains and probe paths get long, so the map moves every key into a bigger table. CPython's dict grows when it is about two-thirds full: a table with 8 slots holds 5 keys, and the 6th key makes it grow.
Common mistakes
- Returning the first pair in the bucket without comparing keys.
get(18)would then return 40, the price of product 3. - Appending on every
put. Then 8 has two pairs, the map has 4 entries instead of 3, andget(8)returns 15 instead of 17. - Saying a hash map is always O(1). That is the average, with a good hash. If every key lands in one bucket, a lookup walks all n keys: O(n).
Follow-up questions
- "Could an attacker make your map slow on purpose?" Yes, if they can choose keys that collide: every lookup becomes O(n). That is why Python salts the hashes of
strandbyteswith a random value per process. A string's hash changes between runs, so never save it or print it in a test. - "Why does growing the table move every key?" The slot depends on the table size. With 8 slots, key 13 goes to
13 % 8, which is 5. With 16 slots it goes to 13. So growing reinserts all n keys: O(n). The size grows by a factor each time, so this is rare, and inserts stay O(1) on average.
What a strong answer covers
Separates the hash, which picks the bucket, from ==, which picks the key. Names chaining and open addressing, and says CPython uses open addressing. Explains load factor, resizing and the O(n) worst case.
Open in interactive practice deck →