Hash Tables

Difficulty
Importance

The problem

Looking up a value by key in an array means scanning every element — O(n) — which is too slow once a collection has more than a handful of items. Hash tables give near-constant-time lookup by turning a key directly into a storage location instead of searching for it.

Why now

Arrays give O(1) access only if you already know the numeric index; a hash table's whole purpose is turning an arbitrary key (a string, an object) into that index. Modular arithmetic already explained how to map an unbounded range of numbers into a fixed number of buckets — a hash table is exactly that idea, with a hash function providing the number to reduce.

Mental model

A hash function converts a key into a number; modular arithmetic reduces that number into one of N buckets; the value lives in that bucket. Lookup, insert, and delete are all 'compute the bucket, go there directly' — no searching, as long as collisions (two keys landing in the same bucket) stay rare, which is exactly the birthday-paradox question probability already answered.

Requires

Helps

Unlocks

Used in

Projects

  • Implement a hash table from scratch with your own hash function and collision handling (chaining), then measure lookup time as load factor increases
  • Use a hash set to solve a duplicate-detection problem in O(n) instead of the naive O(n²) nested-loop approach

Examples

  • A JavaScript object obj[key] is, under the hood, a hash table mapping string keys to bucket locations
  • Two different keys hashing to the same bucket (a collision) is resolved by chaining a small list at that bucket

Resources

Mastery checklist