All pages 5 of 8

The hash table

A coat check that works out each coat's hook from the coat itself, so you can go straight to it.

01234567coat
In life: Work out the hook from the coat, and go straight there.
0catact12dog345fox67
Found act in 3 steps.

Counted: 3 steps

Work the machine

The steps

  1. act adds up to 1 + 3 + 20 = 24, and 24 shared by 8 leaves 0: bucket 0.
  2. Bucket 0 holds cat first, not act, so look at the next word.
  3. The next word is act: that is it.
  4. Found act in 3 steps.
The machine, at the end of the worked example. Press a button to make a move and watch it, one step at a time.
find: about the same, whatever the size2 stepsadd: about the same, whatever the size3 stepsremove: about the same, whatever the size3 steps
The costs, with 8 things inside, counted by running the machine above: one box a step.

What it is

Picture a coat check with 8 hooks. Instead of a ticket, the clerk works out a hook number from your coat. When you come back, the clerk works it out again and goes straight to the right hook.

This is called a hash table. The rule that turns a thing into a number is called a hash. Each hook is called a bucket.

How a move works

Here the things are short words. Give each letter its place in the alphabet, so a is 1 and z is 26. Add them up and share the total by 8. What is left over is the bucket.

For cat, 3 and 1 and 20 make 24. Share 24 by 8 and nothing is left, so cat goes in bucket 0. Dog makes 26, which leaves 2, so dog goes in bucket 2.

Now put act. Its letters add up to 24 as well, so it lands in bucket 0, just behind cat. To get act back, work out the bucket, look at cat, then look at act. That is 3 steps.

Where you meet it

Hash tables are behind the names in your phone, the words in a spell checker and the logins on a website. Most coding languages have one built in, called a dictionary or a map.

Watch out for

Words made of the same letters, like cat and act, land in the same bucket here. That is because adding up ignores the order of the letters. When lots of words share a bucket, a find has to look through them all. A real hash mixes the order in, so the words spread out.