How Hash Tables Work
Average O(1) lookups — the data structure hiding behind every dictionary.
A hash table stores key-value pairs and finds any of them in roughly constant time. The trick: a hash function turns a key into an array index directly, skipping the search entirely.
Legend — how to read this diagram
How a lookup works
- Hash the key. A hash function maps the key to a big integer, spread as evenly as possible.
- Modulo the size. That integer mod the array length gives a bucket index.
- Store or fetch. The value lives in that bucket. To read, hash again and jump straight there.
- Handle collisions. Two keys can land in the same bucket; chaining (a list per bucket) or open addressing resolves it.
The trade-offs
Load factor. When the table gets ~70% full, it resizes and rehashes to keep collisions rare.
Worst case O(n). A bad hash (or adversarial keys) can pile everything into one bucket.
No ordering. Iteration order is arbitrary — use a tree map if you need sorted keys.
Don't search for the key — compute exactly where it must live.
No comments:
Post a Comment