Skip to content

Collisions, load factor and resizing

Working knowledgeUnder the hood

Two different keys can land in the same bucket, and every hash map has a plan for it. Here is how chaining and probing handle the clash, and why the table grows long before it is full.

01 Two keys, one bucket

A map with 8 buckets squeezes every hash into a number from 0 to 7. There are endless possible keys and only 8 buckets, so some keys must share. Two keys in one bucket is a collision.

With the toy hash from the previous tutorial (add up the character codes), "ana" hashes to 304 and "eve" to 320. Different hashes, but 304 % 8 and 320 % 8 are both 0.

Even a perfect hash cannot avoid this. If keys land in random buckets, collisions show up much sooner than you might guess:

Chance that at least two keys share a bucket, 8 buckets, keys placed at random
KeysChance of a collision
212.5%
334.4%
459.0%
579.5%
692.3%

Four keys in eight buckets already collide more often than not. This is the birthday problem, and it is why a map must handle collisions as normal work, not as a rare error.

02 Chaining: each bucket holds a list

The first fix: let each bucket hold a small linked list, its chain. A put hashes to the bucket, walks the chain looking for the key, and adds a new entry if it is not there. A get walks the same chain and compares each entry.

Storing "eve" with chaining
Step 1 of 4
Compares 0
Buckets · 8, each a chain
0ana: 31
1bo: 25
2empty
3dan: 40
4empty
5empty
6empty
7mia: 29
  • comparing now
  • checked, not it
  • just stored

ages["eve"] = 22 is called. Four keys are already stored, one per bucket, and bucket 0 holds "ana". Nothing is read yet.

"eve" key

Java’s HashMap uses chaining. Since Java 8, a chain that grows past 8 entries is turned into a balanced tree (once the table has at least 64 buckets), so even a badly crowded bucket costs a few compares, not hundreds.

03 Open addressing: try the next slot

The second fix keeps one entry per slot and no lists at all. If a key’s home slot is taken, the map probes other slots in a fixed order until it finds a free one. The simplest order is the next slot, then the next: linear probing.

Storing "eve" with linear probing
Step 1 of 4
Probes 0
Slots · 8, one entry each
0ana
1bo
2empty
3dan
4empty
5empty
6empty
7mia
  • probing now
  • taken, move on
  • stored here

Same four keys, but now every slot holds at most one entry. ages["eve"] = 22 needs a home. Nothing is probed yet.

"eve" key

A lookup follows the same path and stops at the first empty slot, because the key would have been stored there. Looking up "ivy", which also hashes to slot 0 and was never stored, now checks slots 0, 1, 2 and 3 before slot 4 proves it is absent. Taken slots bunch together into clusters, and clusters make misses slow.

CPython’s dict uses open addressing, but not the next slot: it jumps around in an order driven by the hash’s higher bits, which breaks up clusters.

ChainingA list per bucketSimple deletes, and it degrades gently when crowded. Each entry is a separate allocation with a pointer, which is harder on the CPU cache.
Open addressingOne flat arrayEntries sit side by side, which is cache-friendly and compact. Misses slow sharply as the table fills, and deletes need care.

04 Load factor: how full is too full

The load factor is entries divided by buckets. With chaining, it is the average chain length. With open addressing, it is the share of slots taken, and it can never pass 1.

For linear probing with a good hash, Knuth’s classic estimates give the expected number of slots a lookup checks. The cost of a miss explodes as the table nears full, because a miss has to walk to the end of a cluster:

Expected probes with linear probing (Knuth’s estimates)
Load factorLookup that finds the keyLookup for a missing key
0.251.21.4
0.501.52.5
0.752.58.5
0.905.550.5
0.9950.55,000.5

Up to about three-quarters full, both kinds of lookup take a handful of probes. Past that, misses get expensive fast. So maps pick a limit and grow the table before reaching it.

Java HashMap0.75Grows when entries exceed 75% of the bucket count. You can pass a different limit to the constructor.
CPython dictabout 2/3Grows when the table is about two-thirds full. It probes, so it keeps misses short by staying emptier.

05 Resizing: a bigger table, every key moved

Growing a hash table is like growing an array: allocate a bigger one, usually twice the size, and move everything. But a key cannot be copied to the same position, because its bucket depends on the table size. Each key’s bucket is worked out again from its hash.

One put that grows the table
Step 1 of 7
Buckets 4Load 0.75
Old table · 4 buckets
012
19
2empty
37
New table · 8 bucketsnull: no table yet
  • just placed
  • moving now
  • moved out

A map of integer keys, where the hash of a number is the number itself (as for Java’s Integer and small Python ints). 3 entries in 4 buckets: load 0.75. The limit is 0.75.

3 entries

With power-of-two sizes, doubling means each key either keeps its bucket number i or moves to i + old size, depending on one more bit of its hash. Java’s HashMap uses this to split each chain in two without recomputing the hashes. As with arrays, doubling keeps the average cost of a put constant: the big moves are rare enough to share out.

06 Watch a Python dict resize

Print the size of a dict each time it changes as you add keys.

grow_dict.py
import sys
d = {}
last = sys.getsizeof(d)
print(f"len 0: {last} bytes")
for i in range(30):
d[i] = i
size = sys.getsizeof(d)
if size != last:
print(f"len {len(d)}: {size} bytes")
last = size
Shell
$ python3 grow_dict.py
len 0: 64 bytes
len 1: 224 bytes
len 6: 352 bytes
len 11: 632 bytes
len 22: 1168 bytes

This is CPython 3.14 on a 64-bit machine. The first key allocates 8 slots, which may hold 5 entries (two-thirds of 8, rounded down). The 6th key grows the table to 16 slots, which hold 10; the 11th grows it to 32, which hold 21; the 22nd to 64. The jumps land right at about two-thirds full.

07 When it bites

Constant-time lookups depend on keys spreading out. If many keys share one bucket, every lookup in it is a linear search, and a map of a million entries can be as slow as a list.

int hashCode() { return 1; }A hash that gives everyone the same bucketIt is legal, since equal objects still get equal hashes, but every key collides. Use the language’s helpers, such as Objects.hash(a, b) in Java, that mix every field.
Collisions on purposeIf an attacker can choose the keys, for example form fields a server puts in a map, they can pick keys that collide and make each request slow. This is a hash-flooding attack. Randomised string hashes (CPython since 3.3) and Java’s tree buckets are the main defences.
Emptying a slot on deleteWith open addressing, clearing a slot breaks every probe path that ran through it: a lookup would stop there and miss keys stored further on. Deletes leave a marker, a tombstone, that lookups skip and inserts may reuse.
HashMap.newHashMap(1_000_000)Paying for resizes you could skipEach resize moves every entry. If you know the size, ask for room up front (Java 19 added HashMap.newHashMap(n), which allows for the load factor).
Relying on the orderA resize moves keys to new buckets, so Java’s HashMap can iterate in a different order after more puts. CPython’s dict keeps insertion order because its entries live in a separate array from its slots.

08 Check yourself

Question

In the linear probing table above, you delete "bo" by simply emptying slot 1. Then you look up "eve" (home slot 0, stored in slot 2). What happens?

Question

A Java HashMap has 16 buckets and the default load factor of 0.75. Which put of a new key makes it resize?

Question

Why does an open-addressing table grow while a quarter or more of its slots are still free?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?