How do you reach the first pair to check?

Finding the first pair to check

Elena Ruiz

How a hash table finds a value

For key 5, read position 1 in the array and follow its reference to 1: oak, the first pair to check.

Transcript

When you look up key 5, you go straight to position 1. What's stored there tells you where to start looking for a pair.

See position 1 here? That's the home index for key 5, the position assigned to that key. So you read position 1 directly in the array and skip the other 3 positions. This spot is a bucket because it's where you look for all the pairs that share a home index. Every pair with home index 1 belongs to this bucket. What you read here tells you how to reach a pair stored outside this spot. That value is a reference because it points you to a particular pair you can reach. See how the arrow starts inside the cell, right where the reference is stored.

Now suppose no pairs belonged to bucket 1: you'd still read the same cell, but it'd be empty. With no first pair to point to, that bucket would have no reference for you to follow.

Back in our table, bucket 1 does hold a reference to its first pair. Follow that reference and you reach the oak pair, with key 1 and value oak. The pairs in this bucket are linked in order, so the next link takes you from the oak pair to the ash pair. Together those linked pairs form a chain that starts right where the reference points. So the oak pair comes first in this chain. That means when you look up key 5, you read only position 1 in the array and follow its reference to the oak pair as your first pair to check.