Skip to the workspace
Pebellslearn by building
Data Structures in Memory  ›  Capstone Project

Hash Tables — Jump Straight to a Key

Hash Table 12 minA hash table turns a key into a number with a hash function, reduces it to a bucket index, and stores the value in that bucket so lookups usually take one step.

computer science / Hash Tables — Jump Straight to a Key

Explore each scene at your own pace.

01 · The rule

The rule

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.

  1. Hash the key: hash("priya") might give 2817.
  2. Reduce it to a bucket index with the remainder: with 8 buckets, 2817 mod 8 = 1.
  3. 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.