Hashing · Exercise 68 of 100

Hash map from scratch

A hash map stores each key with a value and uses the key's hash to choose a bucket. One way to handle keys that share a bucket is to keep a list there and compare the full keys. When storing a value, update the matching pair if the key is already in the list, or add a new pair if the key is missing.

Try it yourself

A seed shop uses a stock map that groups plant names by their first letter. In order, it stores 4 for fern, 9 for fig, and 7 for fern. What value does a lookup for fig return?

One-step hint

Inside the bucket for f, keep a separate row for each full plant name. On the last write, update only the matching row.

Worked solution
  1. Fern and fig both start with f, so their pairs go into the same bucket. The names differ, so each keeps its own value.
  2. Storing 7 changes only the pair for fern. Looking up fig finds its pair and returns 9.
DSA compiler