TL;DR
A hash function takes a key, such as a name or an ID, and returns a whole number in a fixed range, such as 0 to 9. The number says which slot to look in, so you can go straight to the right place instead of checking every entry. A good hash function spreads different keys evenly over the slots, so no slot gets crowded.
Where you'll see it: the hash table behind Python's dict, the index of a database, and the duplicate detection that
decides whether two files are the same.
Intuition
Start from a question you already know
Suppose you own a shoe rack with 10 numbered slots and you want to find your shoes in one step. You could decide that shoes go in the slot that matches the last digit of the shoe's model number. Model 4731 goes to slot 1, model 2208 goes to slot 8. When you want model 4731 you do not search the rack. You compute the slot and look there.
A hash function is that rule. The key is the model number, the function is "take the last digit", and the slot is the result. The rack is an Array of slots, and the whole arrangement is called a Hash Table.
What makes a rule good
The rule has to do two things. It must be fast to compute, so the lookup stays cheap. And it must spread the keys out. If every shoe ends in 0, every shoe lands in slot 0 and the rack is no faster than a pile on the floor. A good rule spreads the keys so that each slot gets about the same number of them. Spreading is the job the rest of this lesson keeps returning to.
The math
The definition
A hash function is a map
where is the set of all possible keys, and is the number of slots. The output is the slot index for key . The map is deterministic: the same key always gives the same slot. That is what makes lookups work.
The division method
The simplest common choice treats the key as a whole number and takes its remainder after division by :
Here is the remainder when is divided by , the same clock arithmetic as in Modular Arithmetic. The result always lies between 0 and .
Keys that are not numbers, such as the string "cat", are first turned into whole numbers. One simple way is to add the character codes. Each letter has a code, for example "c" is 99 and "a" is 97 in the standard ASCII table, so "cat" becomes .
Why spreading matters: the load factor
Suppose keys are stored in slots, and the keys land in slots as if each slot were equally likely. The average number of keys per slot is the load factor
Under this assumption, the chance a given key lands in a given slot is . This is the Uniform Distribution assumption: every slot is equally likely. When a slot already holds a key, the newcomer is placed in the same slot and the slot becomes a short list (this scheme is called chaining). Two keys sharing a slot is called a collision. The average list has about items, so a lookup costs about checks on top of computing the hash.
The point of a good hash function is to make the uniform assumption true for the keys you actually have. A bad function breaks it and makes the lists long.
Worked examples
Use slots and four keys: 12, 25, 31 and 40.
- , since . Key 12 goes to slot 5.
- , since . Key 25 goes to slot 4.
- , since . Key 31 goes to slot 3.
- , since . Key 40 also maps to slot 5.
Keys 12 and 40 collide in slot 5, so slot 5 now holds a two-item list. Slots 0, 1, 2 and 6 are empty. The collision is ordinary: with four keys and seven slots, collisions are common even when the function is fine. Looking up 40 means computing , then checking the two items in slot 5.
Use the character-sum rule from above with slots. Hash the two words "cat" and "act".
- "cat": , and .
- "act": the same three letters in a different order, so the same sum, , and the same slot, 2.
Two different words land in the same slot every time. The rule ignores order, so every anagram collides. For a dictionary of English words, many more pairs collide, and the table becomes uneven. The fix is a rule that depends on the position of each character: multiply the running total by a fixed number before adding the next character. With 31 as the multiplier, "cat" gives and "act" gives . With slots these land in slots and , while the plain sum sends both to . The anagrams now separate.
Store one million keys in a table with slots. The load factor is
- .
- Under the uniform assumption, a slot is empty with probability about . So roughly 38 percent of slots stay empty.
- The average list length is about 0.95, so the typical lookup checks about one item after computing the hash.
With a good hash function, a lookup in a table of a million keys therefore costs about the same as a lookup in a table of ten keys. This is the source of the speed claim: the cost depends on the load factor, not on itself, as long as you keep large compared with . The cost of the operations is analysed with Big-O Notation.
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| Keys share a pattern, such as all ending in 0, and is a power of 10 | Most keys land in a few slots | Choose to be a [[prime-number |
| The hash ignores key order, such as a plain character sum | Anagrams and similar keys collide | Use a rule that mixes position, such as a Polynomial hash (Example 2) |
| grows while stays fixed, so rises | Lists get long and lookups slow down | Resize the table when passes a threshold, often around 0.75 |
| An attacker chooses keys that all collide | Lookups become slow, a risk for servers that take keys from users | Use a randomly chosen hash function from a family, called universal hashing |
| You need the key to be hard to forge or reverse | A fast table hash offers no protection | Use a Cryptographic Hash Function, which is much slower |
The table hash is built for speed and for spreading keys, not for security. A cryptographic hash has stronger properties but costs much more to compute, so the two are used for different jobs.
History
Hash tables appeared in the early 1950s. Hans Peter Luhn at IBM is usually credited with the idea of placing records by a computed address and handling collisions with chains. The name "hash" comes from chopping and mixing the key, as in the cooking sense of the word. Later work, notably by Carter and Wegman in 1979, formalised universal hashing, which gives a guarantee on collisions for a randomly chosen function. Hashing became a standard tool in compilers, operating systems and databases, and most programming languages now ship a hash table in their standard library.
Recap
A hash function maps a key to a slot using a rule that is fast and spreads keys evenly. The division method, , is the simplest rule. The load factor sets the expected list length, so keeping large relative to keeps lookups fast. Next, read about the Hash Table that uses these rules, and the Cryptographic Hash Function that trades speed for hard guarantees.
Check yourself
QuestionRecall. What does a hash function return, and what is it used for in a hash table?Show answer
It returns a whole number between 0 and for a key. That number is the index of the slot where the key is stored. Lookup computes the same number and goes straight to that slot, instead of searching all entries.
QuestionComputation. Using , find the slot for the keys 20, 29 and 47. Which keys collide?Show answer
- , so slot 2.
- , so slot 2.
- , so slot 2.
All three keys collide in slot 2. They are all congruent to 2 mod 9, so the division method sent them to the same place. Keys that differ by a multiple of 9 always collide under this rule.
QuestionWhy. Why does a table with 1,000 keys in 10 slots slow down, even if the hash function is good?Show answer
The load factor is . Every slot holds about 100 keys on average, so a lookup checks about 100 items after computing the hash. The hash function cannot help when there are more keys than slots. The fix is to grow so that stays small.
QuestionApplied. A server stores user-supplied keys in a hash table. Why might a fixed, public hash function be a problem, and what is a remedy?Show answer
An attacker who knows the function can pick keys that all land in one slot. Every lookup then becomes a long scan, which can slow the server to a crawl. A remedy is universal hashing: choose the hash function at random from a family when the table is created, so an attacker cannot predict which keys collide. The table stays fast on average for keys the attacker did not choose.