← All animations

๐Ÿ—ƒ๏ธ Hash Maps

A hash map stores key โ†’ value pairs and finds any of them almost instantly. The trick is a tiny hash function: it folds a key down to a single number, and modulo the array size turns that number into a bucket index. No scanning โ€” you compute exactly where a key lives. Below, watch keys drop into buckets, collide, chain, probe, and trigger a resize.

1. Insert & look up โ€” compute the bucket, jump straight to it

Type a key and a value, then Insert. The key is fed through a small hash function to a big number; we take that mod 8 to pick a bucket, and the pair drops in. To find it again, we re-hash the same key, jump straight to that bucket, and read the value โ€” that's the O(1) average lookup. No walking the array.

hash("cat") = โ€ฆ mod 8 = โ€ฆ

2. Collisions โ€” chaining, probing, load factor & resize

Two different keys can hash to the same bucket โ€” a collision. There are two classic fixes. Chaining hangs a linked list off the bucket; open addressing probes forward to the next free slot. As the load factor (entries รท buckets) climbs, chains lengthen and probes run longer, dragging lookups toward O(n). Cross a threshold and the table resizes โ€” doubles its buckets and rehashes everything to spread keys thin again. Hit Add colliding key to force a pile-up.

load 0.00 ยท 0 / 8 buckets avg lookup ~1 step

3. Why it's fast โ€” and where it powers everything

A hash map trades a little arithmetic for the right to skip searching. Compute the bucket, look there, done.

O(1) average. With a good hash and a sane load factor, most buckets hold zero or one entry, so insert / look up / delete take a handful of steps no matter how big the map gets โ€” 1,000 keys or 1,000,000, the cost barely moves.
O(n) worst case. If every key hashes to the same bucket, the chain becomes one long list and lookups degrade to a linear scan โ€” exactly the search we were trying to avoid. A good hash + resizing keeps this from happening.
A good hash spreads keys evenly. The goal is to scatter keys uniformly across buckets so no single one gets crowded. Small changes in the key should change the hash a lot โ€” similar keys must land in very different buckets, not clump together.
Where they power things. Language dictionaries / objects (Python dict, JS objects, Java HashMap), database hash indexes, caches (memcached / Redis), deduplication, and symbol tables in compilers โ€” all lean on this same key โ†’ bucket trick.