Search

Search papers and lessons

Hash Function

Level 2 · 10 min read

A hash function turns any key into a number in a fixed range, so you can jump straight to a storage slot instead of searching for the key.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Algorithms
  • Sign in to see your progress

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

h:U→{0,1,…,m−1}h : U \to \{0, 1, \ldots, m - 1\}

where UU is the set of all possible keys, and mm is the number of slots. The output h(k)h(k) is the slot index for key kk. 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 mm:

h(k)=k mod mh(k) = k \bmod m

Here k mod mk \bmod m is the remainder when kk is divided by mm, the same clock arithmetic as in Modular Arithmetic. The result always lies between 0 and m−1m - 1.

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 99+97+116=31299 + 97 + 116 = 312.

Why spreading matters: the load factor

Suppose nn keys are stored in mm 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

α=nm.\alpha = \frac{n}{m}.

Under this assumption, the chance a given key lands in a given slot is 1/m1/m. 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 α\alpha items, so a lookup costs about α\alpha 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

Example
Example 1: the division method by hand (tiny)

Use m=7m = 7 slots and four keys: 12, 25, 31 and 40.

  1. 12 mod 7=512 \bmod 7 = 5, since 12=7+512 = 7 + 5. Key 12 goes to slot 5.
  2. 25 mod 7=425 \bmod 7 = 4, since 25=3⋅7+425 = 3 \cdot 7 + 4. Key 25 goes to slot 4.
  3. 31 mod 7=331 \bmod 7 = 3, since 31=4⋅7+331 = 4 \cdot 7 + 3. Key 31 goes to slot 3.
  4. 40 mod 7=540 \bmod 7 = 5, since 40=5⋅7+540 = 5 \cdot 7 + 5. 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 40 mod 7=540 \bmod 7 = 5, then checking the two items in slot 5.

Example
Example 2: why the character sum is a weak hash

Use the character-sum rule from above with m=10m = 10 slots. Hash the two words "cat" and "act".

  1. "cat": 99+97+116=31299 + 97 + 116 = 312, and 312 mod 10=2312 \bmod 10 = 2.
  2. "act": the same three letters in a different order, so the same sum, 312312, 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 (99⋅31+97)⋅31+116=98,262(99 \cdot 31 + 97) \cdot 31 + 116 = 98{,}262 and "act" gives (97⋅31+99)⋅31+116=96,402(97 \cdot 31 + 99) \cdot 31 + 116 = 96{,}402. With m=7m = 7 slots these land in slots 98,262 mod 7=398{,}262 \bmod 7 = 3 and 96,402 mod 7=596{,}402 \bmod 7 = 5, while the plain sum 312312 sends both to 312 mod 7=4312 \bmod 7 = 4. The anagrams now separate.

Example
Example 3: a realistic table

Store one million keys in a table with m=220=1,048,576m = 2^{20} = 1{,}048{,}576 slots. The load factor is

  1. α=1,000,000/1,048,576≈0.954\alpha = 1{,}000{,}000 / 1{,}048{,}576 \approx 0.954.
  2. Under the uniform assumption, a slot is empty with probability about e−α=e−0.954≈0.385e^{-\alpha} = e^{-0.954} \approx 0.385. So roughly 38 percent of slots stay empty.
  3. 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 nn itself, as long as you keep mm large compared with nn. The cost of the operations is analysed with Big-O Notation.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Keys share a pattern, such as all ending in 0, and mm is a power of 10Most keys land in a few slotsChoose mm to be a [[prime-number
The hash ignores key order, such as a plain character sumAnagrams and similar keys collideUse a rule that mixes position, such as a Polynomial hash (Example 2)
nn grows while mm stays fixed, so α\alpha risesLists get long and lookups slow downResize the table when α\alpha passes a threshold, often around 0.75
An attacker chooses keys that all collideLookups become slow, a risk for servers that take keys from usersUse a randomly chosen hash function from a family, called universal hashing
You need the key to be hard to forge or reverseA fast table hash offers no protectionUse 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, k mod mk \bmod m, is the simplest rule. The load factor α=n/m\alpha = n/m sets the expected list length, so keeping mm large relative to nn 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 m−1m - 1 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 h(k)=k mod 9h(k) = k \bmod 9, find the slot for the keys 20, 29 and 47. Which keys collide?Show answer
  1. 20=2⋅9+220 = 2 \cdot 9 + 2, so slot 2.
  2. 29=3⋅9+229 = 3 \cdot 9 + 2, so slot 2.
  3. 47=5⋅9+247 = 5 \cdot 9 + 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 α=1000/10=100\alpha = 1000/10 = 100. 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 mm so that α\alpha 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.

Sources

Hash Function — explained simply | ungoon.me