The idea
With 4 buckets, keys 0 and 4 share a bucket. Lookup of 0 still returns 1.
Separate chaining stores a list of key-value pairs in each bucket. The hash of the key picks the bucket. Insert appends a pair, or replaces the value if the key is already in that list. Lookup scans the list and compares keys. With a 4-bucket table, hash(0) % 4 and hash(4) % 4 are both 0. Inserting 0 and then 4 places both pairs in one chain. A later lookup of 0 walks that chain and returns 1. The library ChainingHashTable does this, and len stays 2 because the keys differ.
A worked trace
| Step | State | What changed |
|---|---|---|
| Bucket | index = 0 | Key 0 joined bucket 0. |
| Bucket | index = 0 | Key 4 joined bucket 0. |
| Bucket | index = 0 | Lookup of 0 returns 1. |
| Bucket | index = 0 | Lookup of 4 returns 2. |
Why it is correct
The hash is only a suggestion of where to look. Equality of keys is the real test. Two keys that share a bucket remain distinct as long as the chain stores both pairs. Lookup does not stop at the first pair. Insert of a new key appends, which preserves the pairs already there. Insert of an existing key overwrites that pair's value instead of appending a duplicate. That is why a lookup that scans from the front finds the current value.
A common mistake
A shared bucket is a collision, not a missing key.
What it costs
The load factor is the number of keys divided by the number of buckets. With n keys and b buckets the average chain is that load factor, n / b. One lookup is Θ(1 + n / b) comparisons when keys spread evenly, and Θ(n) when every key lands in one bucket. Resizing when the load factor grows keeps the average chain short, and the resize itself copies every pair once. Extra memory is Θ(n + b) for the pairs and the bucket lists. Expected Θ(1) is not a worst-case promise.
Keys 0 and 4 share a bucket because the bucket count is 4 and both hashes are multiples of 4. A third key 8 would append behind them. Lookup of 0 would then compare 0, skip 4, and skip 8 only if 0 were missing. The chain length is the cost you pay.
Run it
from bitsandbytes.hash_tables.chaining import ChainingHashTabletable = ChainingHashTable(bucket_count=4)table[0] = 1table[4] = 2print(table[0], table[4])# prints: 1 2 Practice and next step
Open Hash tables with linear probing next. Linear probing stores that collision in the next open slot, and a tombstone keeps the walk going.