Hash Tables — Jump Straight to a Key
A phone's contacts app finds "Priya" instantly among thousands of names. Scanning every contact would be slow, and keeping them sorted still needs a search. A hash table does better: it computes where Priya must be and looks only there. Python's dict, JavaScript's Map and Java's HashMap all work this way.
The rule
Hash the key, take it mod the bucket count, look in one bucket.
A hash table is an array of buckets plus a hash function: a function that turns any key into a whole number.
- Hash the key:
hash("priya")might give 2817. - Reduce it to a bucket index with the remainder: with 8 buckets, 2817 mod 8 = 1.
- Store or look up in bucket 1 only.
Because a lookup repeats exactly the same calculation, it lands in the same bucket the value was stored in. That is why the golden rule of hashing is: equal keys must always produce equal hashes.
Sometimes two different keys land in the same bucket. That is a collision, and it is normal. A common fix, chaining, lets each bucket hold a small list of entries; the table compares keys inside that list to find the right one.
bucket 0: (empty)
bucket 1: ("priya", 555-0101)
bucket 2: ("arun", 555-0142) -> ("meera", 555-0199) <- a collision
bucket 3: (empty)When buckets start to fill up, the table grows (often doubling its bucket count) and re-places every entry, which keeps the chains short.