How a hash map works: hashing, collisions and cost

Video lessonComing soon

1 What happens inside a map

The previous lesson counted values with a hash map and took each lookup as about one step. This lesson opens the map up to see how it manages that.

The inside also explains three things that surprise students:

  • A map can get slow. On some inputs, its one step becomes thousands.
  • Some values cannot be keys. In Python, a list as a key is a Runtime Error.
  • Keys come out in a strange order. A loop over a map rarely gives them sorted.

2 An array of buckets

Underneath, a hash map is a plain array. Each box of the array is a bucket. Our toy map starts with 8 buckets, numbered 0 to 7.

To store a key, the map needs a bucket number for it. A hash function turns the key into a whole number, the key's hash. Then hash % 8 picks the bucket, because the remainder is always between 0 and 7.

Our toy hash function adds up the letters of a word, with a = 1, b = 2, and so on up to z = 26. We put in four keys:

KeyLettersHashBucket, hash % 8
cat3 + 1 + 20240
dog4 + 15 + 7262
eel5 + 5 + 12226
ant1 + 14 + 20353
cat01dog2ant345eel67
Four keys in 8 buckets, each in the bucket its hash picks

To look up dog later, the map repeats the same steps. It calculates 26, takes 26 % 8 = 2 and looks in bucket 2. It never checks the other buckets. So a lookup costs about one step, however many keys the map holds.

Here is the toy hash function:

With size 8, every tab returns 0 for cat, 2 for dog, 6 for eel and 3 for ant. Subtracting the code of 'a' turns each letter into its place in the alphabet.

3 Collisions cannot be avoided

The fifth key is owl. Its letters add up to 15 + 23 + 12 = 50, and 50 % 8 = 2. Bucket 2 already holds dog.

cat01dog2ant345eel67owl
owl hashes to bucket 2, where dog already sits

Two keys in one bucket are a collision. No hash function can avoid them all. There are millions of possible words and only 8 buckets, so some words must share.

A good hash function cannot stop collisions, but it spreads keys evenly, so no bucket gets far more than its share. Our toy function is weak at this. The words cat and act have the same letters, so both get the hash 24 at every table size. Real hash functions also mix in each letter's position, so cat and act get very different hashes.

4 Chaining: a short list per bucket

The usual fix is chaining. Each bucket holds a short list of the keys that landed there, each with its value. After owl, bucket 2 holds dog and then owl.

dogbucket 2owl
Bucket 2 after the collision: a list of two keys

A lookup now takes two steps:

  1. Hash the key and take % 8 to find its bucket.
  2. Walk that bucket's list and compare each key with the one we want.

To find owl, the map goes to bucket 2. It compares owl with dog, which is not equal, and then with owl, which is. To find hen, it calculates 8 + 5 + 14 = 27 and goes to bucket 3. The only key there is ant, so hen is not in the map.

With more keys, more lists form. If our map never grew, 11 keys in its 8 buckets would look like this:

0catpig12dogowlgnu3ant45foxyak6eelhog7bat
11 keys in 8 buckets: each bucket holds a list, and some lists are empty

Finding gnu now takes three comparisons: dog, owl, then gnu. The cost of a lookup is the length of one list. While the lists stay short, a lookup is still about one step.

Some maps use open addressing instead: a key that collides tries other buckets of the array until it finds a free one. The ideas in the rest of this lesson hold for both.

5 What real maps keep in a bucket

A list per bucket is the classic picture of chaining. Real libraries differ in the details:

  • C++, C# and JavaScript: a list. Each bucket holds a chain of keys, as in the drawing above.
  • Java: a list that can turn into a tree. When one bucket's list grows past 8 keys, Java turns it into a balanced tree. It does this only once the table has at least 64 buckets. A smaller table grows instead, which spreads the keys out.
  • Python, Rust and newer versions of Go: open addressing. There are no lists. A key that collides takes the next free place that a fixed rule picks.

The tree only matters when many keys share one bucket. Our toy hash gives cub, dim, dog, eat, foe, god, lie, rag and tea the same hash, 26, so all nine land in bucket 2.

012cubdimdogeatfoegodlieragtea34567
As a list: nine keys in one chain
cubdimdogeatfoegodlieragtea
As a tree: the same nine keys in order

In the list, finding tea means comparing it with all nine keys. The tree keeps its keys in order, so at each node a lookup goes left or right. Finding tea takes 3 comparisons: foe, rag, then tea.

Nine keys is a small difference. With 10⁵ keys in one bucket, a list walk takes 10⁵ steps and a tree walk about 17.

Java orders a tree bucket by hash first. Keys with equal hashes, like the nine here, are ordered by their own order when they have one, as strings do.

6 Load factor and resizing

Lists stay short only while the table has room. The load factor is the number of keys divided by the number of buckets. As it grows, more keys share buckets and the lists get longer. The 11 keys in 8 buckets of section 4 have a load factor of about 1.4, and one list is already three long.

So the map grows its array. Our toy map doubles it once an insert would push the load factor past 3/4. Real libraries pick a limit close to this.

Next we add fox, with hash 45 and bucket 5. Now 6 keys sit in 8 buckets, a load factor of exactly 3/4. Then we add bee, the seventh key. The load factor would be 7/8, past 3/4, so the map makes a new array of 16 buckets.

Every key needs a new bucket, because its bucket was hash % 8 and must now be hash % 16. The map takes the keys one by one and puts each into the bucket for hash % 16. This step is called rehashing.

KeyHashhash % 8hash % 16
cat2408
dog26210
eel2266
ant3533
owl5022
fox45513
bee1212
cat01dog2ant34fox5eel67owl
Before: 6 keys in 8 buckets, with owl in bucket 2 behind dog
01owl2ant345eel67
cat89dog1011bee12fox131415
After: 16 buckets in two rows, and bee added in bucket 12

Before the resize, dog and owl shared bucket 2. After it, dog moves to bucket 10 and owl stays in bucket 2, so every list holds one key again.

A resize moves every key, so one insert now and then costs far more than one step. It still averages out. To reach 10⁵ keys, the resizes move 6, then 12, then 24 keys, and so on, up to about 10⁵ in the last one. Each number is double the one before, so the whole sum stays under twice the last one.

That is under 2 × 10⁵ moves for 10⁵ inserts, about two extra moves per insert. So an insert costs O(1) on average. The next lesson shows a dynamic array growing by doubling for the same reason.

7 Average O(1), worst case O(n)

OperationAverageWorst case
InsertO(1)O(n)
Look upO(1)O(n)
RemoveO(1)O(n)

The map also uses O(n) space for its keys and buckets.

The average assumes the hash function spreads the keys well, so each list holds about one key. The worst case is every key in the same bucket. Then the map is one long list, and a lookup walks all n keys, as a search through an unsorted array does. Java's tree buckets cut this worst case to about O(log n) for keys that have an order, such as numbers and strings.

A loop of 10⁵ lookups shows the gap. With short lists, it takes about 10⁵ steps. With every key in one bucket, it takes about 10¹⁰ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE.

Short lists10⁵One long list10¹⁰about 1 second
10⁵ lookups, on a scale where each mark is ten times the last

With the library's own hash function, ordinary keys do not pile up like this by chance. A carefully crafted input can make many keys collide, but for the problems here we count each map operation as O(1).

8 What a key needs

The two lookup steps show what a key type needs:

  • A hash. It picks the bucket. Equal keys must give equal hashes, or the map looks in the wrong bucket.
  • Equality. It finds the key inside the bucket's list.
  • No changes after insertion. The key sits in the bucket of its old hash. If the key changes, its hash changes, and a lookup goes to a different bucket and misses it.

Numbers and strings have all three in every language. Python enforces the third rule. A list can change, so it cannot be a key. A tuple cannot change, so it can.

Pairs come up often, such as a grid cell as (row, column). A pair needs a hash of our own before it can be a key. The next section shows how to make a key type of our own.

9 A hash for your own type

Sometimes the key is a type of our own, such as a Cell with a row and a column. Then we tell the map two things: how to hash a cell, and when two cells are equal. The two must agree. Two equal cells must give the same hash, or a lookup goes to the wrong bucket.

A common recipe builds the hash from the fields: take the first field's hash, multiply it by 31, and add the next field's hash. For Cell(2, 3) that gives 31 × 2 + 3 = 65.

The multiplication matters. Adding alone gives (2, 3) and (3, 2) the same hash, 5. That is the same weakness cat and act showed. With the 31, (3, 2) gets 95.

Here each language counts visits to cells, with (2, 3) visited twice:

C++

A hash struct and ==. unordered_map takes the hash as its third type. Without one, unordered_map<Cell, int> does not compile, and neither does a pair<int, int> key.

Override both equals and hashCode. With only equals, every new cell gets a different default hash, so get(new Cell(2, 3)) returns null. A record writes both for us.

__eq__ and __hash__. Hashing a tuple of the fields is the simple way. A plain tuple key also works.

No custom hash. A Map compares objects by identity, so visits.get([2, 3]) gives undefined. We turn the key into a string.

No custom hash. A struct whose fields compare with == is a key as it is.

derive. #[derive(Hash, PartialEq, Eq)] writes both from the fields.

Override Equals and GetHashCode. HashCode.Combine mixes the fields. A record or an (int, int) tuple gives both for free.

10 Order and the sorted map

A hash map places keys where their hashes send them, so a loop over it does not give them sorted.

When we need the keys in order, a sorted map keeps them sorted. It is a balanced tree, not an array of buckets, so each operation costs O(log n), about 17 steps at n = 10⁵. In return, it can give the smallest key, the largest key, or the first key after a given one.

C++

Loop order. A loop gives the keys in the order they were added.

Sorted map. None is built in, so we sort the keys once at the end.

Loop order. A loop gives the keys in the order they were added.

Sorted map. None is built in, so we sort the keys once at the end.

Loop order. A different order on each run, on purpose.

Sorted map. None is built in, so we sort the keys once at the end.

Loop order. A different order on each run, on purpose.

Sorted map. BTreeMap.

Loop order. No promise, and it can change after a resize.

Sorted map. map.

Loop order. No promise, and it can change after a resize.

Sorted map. TreeMap.

Loop order. No promise, and it can change after a resize.

Sorted map. SortedDictionary.

The problem needsUse
counts of small whole numbers, such as 0 to 10⁵an array, as in the last lesson
counts or values for any other keysa hash map, O(1) on average
keys in order, or the next key after xa sorted map, O(log n)

The habit to keep: count each hash map operation as O(1), and never rely on the order a hash map loops in. When the answer must be in order, sort the keys or use a sorted map.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.