Data structures · hashing

Hash Function Explorer

A hash function turns a key of any size into a number in a fixed range, called the key's hash value or hash code. A hash table uses that number as an array index, so it can store a key and later find it again in one step instead of searching.

H(x) = x % 10

This one maps any whole number to a value from 0 to 9, the index of a slot in a table of 10.

List = [ 11, 12, 13, 14, 15 ]   H(x) = x % 10
Each key goes to the slot named by its last digit.

Two everyday examples

Phone numbers

For a table of 100 slots, use the last two digits: h(k) = k % 100, which is always 0 to 99.

740-427-5000 → 00740-427-5137 → 37614-292-6446 → 46

The first two digits would be a poor choice. Numbers in the same area share them, so most keys would land in a few slots.

Lowercase words

Give each letter a value (a = 1, b = 2, … z = 26), add them up, and take % 100. Different words can give the same sum:

"ad" = 1 + 4 = 5"bc" = 2 + 3 = 5

A weighted sum fixes much of this by making each position count differently, for example h = (31·h + letter) for each letter. Then "ad" = 35 and "bc" = 65.

What makes a hash function good

Deterministic tablesThe same key always gives the same hash value, or you could never find it again.
Fixed output range tablesEvery result fits the table, 0 to m − 1, however large the key is.
Fast tablesA few arithmetic steps. A slow hash cancels the point of hashing.
Uniform tablesKeys spread evenly over all slots instead of clustering, so chains and probe runs stay short.
Avalanche effect securityChanging one digit of the key changes the hash value a lot.
Collision resistance securityIt is hard to find two different keys with the same hash value.
Pre-image resistance securityGiven a hash value, it is infeasible to work out a key that produces it.

The first four are what a hash table needs. The last three matter for security uses, such as storing passwords, where someone may be trying to break the hash on purpose.

Where hash functions are used

Try it: one set of keys, six hash functions

Type whole numbers from 0 to 999,999,999, separated by spaces or commas. Every function below maps them into the same hash space of m slots. Highlighted values are collisions: two or more keys that got the same slot in that column.

30
collision in that column Slot strip: one key two or more empty Click a row to see each function's steps for that key.
Perfect hashing is a seventh kind that you cannot try with arbitrary keys. For a fixed set of keys known in advance, such as the keywords of a programming language, it builds a function that gives every key its own slot, with no collisions at all. A minimal perfect hash also uses exactly as many slots as there are keys. It is hard to construct and must be rebuilt if the key set changes.