Load factor and resizing
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)As a hash table fills up, collisions multiply and lookups slow down. Dynamic resizing doubles array capacity to keep operations running in constant time.
Why a map resizes: load factor threshold
The load factor is the number of entries divided by the number of buckets. When it passes a limit (0.75 in Java), the table grows and every entry is placed again.
A hash table measures how full it is with the load factor, size divided by capacity. Past 0.75 it doubles its array. The program below shows a map growing from capacity 4 to 8.
- Track the count of elements currently stored in the map.
- Before inserting, check if
size + 1exceedsthreshold. - If exceeded, allocate a new array of double the current capacity.
- Rehash every existing entry into the new array.
Example 1 · Dynamic Resizing HashMap Demo
public class ResizingMapDemo { static class Node { String key; int val; Node next; Node(String k, int v, Node n) { key = k; val = v; next = n; } }
private Node[] buckets; private int size; private int capacity; private final double loadFactor = 0.75;
public ResizingMapDemo(int cap) { capacity = cap; buckets = new Node[cap]; size = 0; }
public void put(String key, int val) { if ((double) (size + 1) / capacity > loadFactor) { resize(); } int idx = (key.hashCode() % capacity + capacity) % capacity; for (Node curr = buckets[idx]; curr != null; curr = curr.next) { if (curr.key.equals(key)) { curr.val = val; return; } } buckets[idx] = new Node(key, val, buckets[idx]); size++; }
private void resize() { int newCap = capacity * 2; Node[] newBuckets = new Node[newCap]; for (Node head : buckets) { Node curr = head; while (curr != null) { Node next = curr.next; int newIdx = (curr.key.hashCode() % newCap + newCap) % newCap; curr.next = newBuckets[newIdx]; newBuckets[newIdx] = curr; curr = next; } } buckets = newBuckets; capacity = newCap; }
public int getCapacity() { return capacity; } public int getSize() { return size; }
public static void main(String[] args) { ResizingMapDemo map = new ResizingMapDemo(4); map.put("k1", 1); map.put("k2", 2); map.put("k3", 3); System.out.println("Size: " + map.getSize() + ", Cap: " + map.getCapacity()); map.put("k4", 4); // Exceeds 3/4 threshold, triggers resize System.out.println("Size: " + map.getSize() + ", Cap: " + map.getCapacity()); }}Size: 3, Cap: 4 Size: 4, Cap: 8
What this code does
- Capacity starts at 4 with threshold 4 * 0.75 = 3.
- Inserting 4th key exceeds threshold and doubles capacity to 8.
- Existing entries are rehashed into the larger 8-slot array.
Load factor is the ratio of stored elements to array capacity: size / capacity. Why not allocate a massive array from the start?
A huge array wastes vast memory for small datasets. Never resizing leads to severe collisions and degrades lookups to O(n).
Resizing doubles capacity when load factor exceeds 0.75, keeping chains short. This balance delivers both high speed and modest memory usage.
- Load factor formula:
loadFactor = (double) size / capacity. - Threshold trigger: capacity doubles when size reaches
threshold = capacity * 0.75. - Performance safeguard: resizing keeps average bucket chain length short.
Predict the output
Predict the resize
Read each snippet and pick what it prints.
Round 1 of 3
The cost of rehashing
Growing the array changes hash % capacity, so every entry must be placed again. This is called rehashing. The programs below print indexes before and after growing.
Rehashing: capacity 4 grows to 8
Step 1 of 7
- size
- 3
- capacity
- 4
Example 2 · Observing Index Changes After Rehashing
public class RehashIndexTraceDemo { public static void main(String[] args) { int hash = 13; int oldCap = 4; int newCap = 8; int oldIdx = hash % oldCap; int newIdx = hash % newCap; System.out.println("Old index (cap 4): " + oldIdx); System.out.println("New index (cap 8): " + newIdx); }}Old index (cap 4): 1 New index (cap 8): 5
What this code does
- 13 % 4 equals 1, placing the key in bucket 1.
- 13 % 8 equals 5, relocating the key to bucket 5 in the larger array.
- This proves keys must be rehashed rather than copied to original indices.
Example 3 · Visualizing Key Redistribution Across Resizing
import java.util.Arrays;
public class RehashDistributionDemo { public static void main(String[] args) { int[] keys = {2, 6, 10}; int oldCap = 4; int newCap = 8;
int[] oldBuckets = new int[keys.length]; int[] newBuckets = new int[keys.length];
for (int i = 0; i < keys.length; i++) { oldBuckets[i] = keys[i] % oldCap; newBuckets[i] = keys[i] % newCap; }
System.out.println("Old buckets: " + Arrays.toString(oldBuckets)); System.out.println("New buckets: " + Arrays.toString(newBuckets)); }}Old buckets: [2, 2, 2] New buckets: [2, 6, 2]
What this code does
- In capacity 4, keys 2, 6, and 10 all collide in bucket 2.
- In capacity 8, key 6 moves to bucket 6 while keys 2 and 10 stay in bucket 2.
- Doubling capacity splits clusters and restores short search paths.
Resizing is not a simple array copy because capacity has changed. Bucket index depends on capacity: (hash % newCapacity + newCapacity) % newCapacity. Every existing entry must have its bucket index recalculated and be reinserted.
Consider capacity 4 with threshold 0.75 (maximum 3 items). Keys 2, 6, and 10 all hash to index 2 (2 % 4 = 2). Inserting a 4th key triggers a resize to capacity 8. Rehashing recalculates indices: key 2 stays at index 2 (2 % 8 = 2). Key 6 moves to index 6 (6 % 8 = 6). Key 10 stays at index 2 (10 % 8 = 2). The single crowded cluster of 3 keys splits across buckets 2 and 6.
- Index shift: changing capacity relocates keys to entirely new bucket indices.
- Full traversal: every node must be detached and placed into its new bucket.
- Temporary spike: the resizing operation incurs an O(n) latency penalty.
Amortised O(1) insert complexity
Although resizing takes O(n) time, it occurs infrequently.
Doubling capacity from n to 2n requires n new insertions before the next resize.
Dividing the O(n) rehashing work over n insertions adds only O(1) cost per insertion. Therefore, hash table insertions run in amortized O(1) time.
- Geometric doubling: capacity doubles exponentially (16, 32, 64, 128, ...).
- Amortized analysis: spreading infrequent O(n) costs across n constant operations.
- Result: overall insertion performance remains constant O(1) on average.
Next step
Check your understanding
10 quick questions