Hashing · Exercise 67 of 100

Hash table

A hash table uses a hash function to choose a starting slot for each key. If that slot is taken by a different key, linear probing checks the next slot and wraps around at the end. As long as an empty slot remains, this search will find room for a new key.

Try it yourself

An empty table has slots 0 through 4. Each key starts at the remainder after dividing it by 5. Insert 9, then 4, then 14 using linear probing. In which slot does 14 land?

One-step hint

Draw five slots in a ring. Compute each key's starting slot, then walk forward past occupied slots, wrapping around the ring as needed.

Worked solution
  1. Both 9 and 4 leave a remainder of 4. The key 9 takes slot 4, so the key 4 wraps around to slot 0.
  2. The key 14 also starts at slot 4. Slots 4 and 0 are full, so it lands in slot 1.
DSA compiler

Explore the idea visually in the hash tables lab.