Growing the table
After this: Explain the load factor, why the table grows, and why inserts stay fast on average.
On this page · 7 sections · 4 checks
Chains let keys share a slot. But each chain is a small list, and a lookup has to walk it. What happens if we keep inserting?
Our table has eight slots. With 80 pairs, the chains would hold about ten pairs each, and a lookup might have to compare ten keys. The more pairs we add, the longer the chains get, and the slower every lookup becomes.
Keys keep arriving and the chains keep getting longer. What should the table do?
How full is the table?
To know when to grow, the table needs a way to measure how full it is. It divides the number of pairs by the number of slots. The result is called the . Here it is for a table of eight slots.
| Pairs | Slots | Load factor |
|---|---|---|
| 2 | 8 | 2 ÷ 8 = 0.25 |
| 6 | 8 | 6 ÷ 8 = 0.75 |
| 7 | 8 | 7 ÷ 8 = 0.875 |
A load factor of 1 means that there are as many pairs as slots, so chains hold one pair on average. A higher number means longer chains.
The table in this tutorial grows when the load factor goes above 0.75. Six pairs give exactly 0.75, which is not above it, so nothing happens. The seventh pair gives 0.875, so the seventh insert makes the table grow.
Growing: double, then re-insert
Growing the table is called a , and it has two steps.
- Create a new table with twice as many slots.
- Insert every pair again, into the new table.
Step 2 is the one people forget. Why not copy each pair across to the same slot number? Because a key's slot depends on the number of slots. cat has the hash 312. In a table of 8 slots its slot is 312 % 8 = 0, but in a table of 16 slots its slot is 312 % 16 = 8.
Suppose cat were copied to slot 0 of the new table. A lookup for cat would work out slot 8, find it empty, and answer Nonenull, although cat is stored in the table.
Here are four of the keys, before and after a resize.
| Key | Hash | Slot with 8 slots | Slot with 16 slots |
|---|---|---|---|
cat | 312 | 0 | 8 |
dog | 314 | 2 | 10 |
owl | 338 | 2 | 2 |
fox | 333 | 5 | 13 |
Look at dog and owl. They shared slot 2 before the resize, and now they have a slot each. This is how growing makes chains shorter.
The code
put now checks the load factor after each insert, and _resizeresize does the doubling.
def put(self, key, value): bucket = self.buckets[self._index(key)] for pair in bucket: if pair[0] == key: pair[1] = value return bucket.append([key, value]) self.count += 1 if self.count / self.capacity > 0.75: # load factor above the threshold self._resize()
def _resize(self): old_buckets = self.buckets self.capacity *= 2 self.buckets = [[] for _ in range(self.capacity)] self.count = 0 for bucket in old_buckets: for key, value in bucket: self.put(key, value) # re-insert: new capacity, new slot public void put(String key, int value) { List<Pair> bucket = buckets.get(index(key)); for (Pair pair : bucket) { if (pair.key.equals(key)) { pair.value = value; return; } } bucket.add(new Pair(key, value)); count++; if ((double) count / capacity > 0.75) { // load factor above the threshold resize(); } }
private void resize() { List<List<Pair>> oldBuckets = buckets; capacity *= 2; // capacity and buckets are no longer final buckets = new ArrayList<>(); for (int i = 0; i < capacity; i++) buckets.add(new ArrayList<>()); count = 0; for (List<Pair> bucket : oldBuckets) { for (Pair pair : bucket) { put(pair.key, pair.value); // re-insert: new capacity, new slot } } }Here is how to read it.
- The start of
putis the same as in the last lesson. - After adding a new pair,
putdividescountbycapacity. If the result is above 0.75, it calls _resizeresize. - _resizeresize keeps the old slots, doubles
capacity, and creates a new empty table. It setscountto 0 because the new table is empty. - The loops at the end go through every old pair and call
putfor it.putworks out the slot with the new capacity, and it adds one tocounteach time.
So _resizeresize reuses put. Re-inserting a pair is an ordinary insert. The only thing that has changed is the number we divide by.
Watch it happen
The table below already holds six pairs: cat, dog, fox, emu, ant and owl. owl shares slot 2 with dog. Insert a seventh pair and keep stepping after it lands.
- Insert bee → 9The table holds 6 pairs in 8 slots. Insert a seventh pair and watch what happens after it lands.
- Look up cat
- 0catmaps to3
- 1—
- 2dogmaps to1owlmaps to8
- 3antmaps to6
- 4—
- 5foxmaps to4
- 6—
- 7emumaps to2
Start with the first task above, or try any key.
- count
- 6
- load
- 0.75
- compares
- 0
What it costs
A resize re-inserts every pair, so the one insert that causes it is O(n): its work grows with the number of pairs. If that sounds slow, count how often it happens.
Start with 8 slots and keep inserting. Resizes happen at the 7th, the 13th and the 25th insert. They re-insert 7, 13 and 25 pairs, which is 45 in total. So 25 inserts cause 45 re-inserts, fewer than two per insert. Each resize doubles the table, so the next one takes about twice as long to come.
This means that most inserts are cheap, a few are expensive, and the average stays small however many pairs you add. The name for this is . "Amortized" means averaged over many operations. The arrays lesson Why appending stays fast explains the same idea with a yearly fee. The lesson How fast is a hash map, really? puts all the costs together.
Check yourself
After the resize the table has 16 slots. Where does cat (sum 312) live now?
Why can't the resize copy the eight old slots into the first eight of the sixteen new slots?
Inserts are called amortized O(1). What does that mean?
Connect
- Say what the load factor is and the limit this table uses.
- Explain why a resize must re-insert every pair, and cannot only copy them.
- Say what amortized O(1) means for inserts.