How a hash table finds a key


A hash table is a way to store key–value pairs so that finding a value by key usually takes about the same small amount of work, no matter how many pairs you have. The trick is not magic memory: it is a rule that turns a key into a shelf number, then a short search on that shelf.

Under the hood the table keeps an array of buckets. Each key is fed through a hash function that returns an integer. That integer is reduced modulo the array length to pick a bucket. Put the pair in that bucket; later, hash the key again and look in the same place.

key ──► hash(key) ──► index = hash % N ──► bucket[index]

If two keys land in the same bucket (a collision), the bucket holds a short list or chain. A lookup then compares keys inside that bucket until it finds a match—or decides the key is missing. When hashes spread keys evenly, buckets stay short and lookups stay fast. When they do not, the worst case slides toward scanning many keys.

Shelf metaphor for hashing into buckets

The durable idea is the index rule: same key, same shelf. Exact collision strategies and hash algorithms change over time; the mental model of “hash, then check one shelf” does not.