What a hash function does and why collisions happen
standardbeginnerA hash function turns a key into a fixed-size integer, which a dict or set uses to pick which internal bucket to store it in. A collision is two different keys landing in the same bucket.
Think of it as
Think of the hash function as an address generator: hash(key) % table_size points at a specific shelf. Two different keys can generate the same shelf number — that is a collision — so the table also stores enough information in that bucket to tell the colliding keys apart once it gets there.
What we're doing: Show two different integer keys colliding into the same bucket once reduced by a small table size.
- 1
- hash(key) % num_buckets is exactly what a hash table does internally to pick a slot.
- 2
- For a small int, hash(n) == n, so the collision here is easy to see by hand: 10, 14, and 18 are all 2 more than a multiple of 4.
2 2 2Why this works: 10, 14, and 18 are three different keys, but 10 % 4, 14 % 4, and 18 % 4 all equal 2 — all three collide into the same bucket. A real hash table still returns the right value for each key; it just has to check more than one candidate in that bucket to do it.
Remember: A hash function maps a key to a bucket index; a collision is two keys sharing a bucket, and too many collisions are what turn O(1) average into O(n) worst case.