Transcript
To find one word among a million sorted ones, binary search from episode five takes about twenty steps. A hash table usually does it in one. Today: how to turn a word straight into a place.
Start with eight buckets, numbered zero to seven. We need a rule that turns any word into one of those numbers. Here's a simple one. Add up each letter's place in the alphabet, divide by eight, and keep the remainder. That rule is called a hash function. Every word drops straight into its own bucket. To find a word later, run the same rule and look in just that one bucket. No need to search the rest.
But sooner or later, two words land in the same bucket. That's called a collision. One fix: each bucket keeps a short chain, and the new word hangs underneath. Another: if the bucket is taken, try the next one, and the next, until you find an empty spot.
Collisions come sooner than you'd think. Picture three hundred sixty-five buckets, one for each day of the year, and drop in people by their birthday. How many people before two share a day? Just twenty-three, and the chance is already better than half. So every hash table has to be ready for collisions.
And as a table fills up, the chains grow longer, and every lookup slows down. So when the table is about three quarters full, it doubles in size, and every word is placed all over again. Moving everything is slow, but it rarely happens. Spread out over all the words, each one still costs just a few steps on average.
A hash table turns a word straight into a place, so finding it takes about one step, however big the table gets. Next time: trees. The folders on your computer, a formula, and four ways to walk through them. See you there.
Next episode: trees, from the folders on your computer to a formula, and four ways to walk through them.