← All coursesDSA Foundations

Lesson 5 of 19

Hash tables

A hash function chooses a bucket for each key. Here the bucket is the remainder after division by 3. Two keys may land in the same bucket.

A bucket narrows the search

A hash table stores a value under a key. A hash function picks the bucket to inspect. Different keys can pick the same bucket, a collision. In the chaining method used here, the bucket holds several entries and a lookup compares their full keys.

Work through an example

Keys 4 and 10 are in bucket 1 of a three-bucket table. You look up 7. How can an occupied bucket still give a miss?

Step-by-step solution
  1. 7 divided by 3 leaves remainder 1, so start in bucket 1.
  2. Check the actual keys. Neither 4 nor 10 equals 7, even though all three keys have the same remainder.
  3. The bucket has no more entries. Report a miss. A crowded bucket means more comparisons per lookup.
JavaScript example
const buckets = [[], [[4, "pen"], [10, "ink"]], []];
function lookup(key) {
  const bucket = buckets[key % buckets.length];
  for (const [storedKey, value] of bucket) {
    if (storedKey === key) return value;
  }
  return undefined;
}
lookup(7); // undefined
DSA compiler

Try it yourself

Finish the animation to unlock this question.

Using key % 3, which key shares a bucket with 4?

Related exercise · Hash table · Take the end-of-stage challenge