← DSA

📈 Rehashing

How a Hash Map Grows — Rehashing
insert → load factor climbs → cross the threshold → double the buckets → every key gets a new index
Speed
Press Play or Step to insert the first key.
0 / 4 = 0.00
┆ threshold 0.75
key
hash
buckets
4
index
set(key, value):
i = hash(key) % buckets.length
buckets[i].push([key, value]); n += 1
if n / buckets.length > 0.75: // load factor
grow()
 
grow():
old = buckets
buckets = new Array(old.length * 2) // double
for (k, v) in old: // EVERY entry
i = hash(k) % buckets.length // new modulus → new index
buckets[i].push([k, v])
Items (n)
0
Buckets (m)
4
Load factor
0.00
Rehashes
0
Keys re-placed
0

What a Rehash Costs
OperationCostWhy
Insert, no rehashO(1)hash, jump, push
The insert that triggers a rehashO(n)every existing entry is re-placed
Insert, amortisedO(1)doubling means each key is moved ~twice over the whole build
Building a map of n itemsO(n)total, not O(n²)
Doubling is what makes it amortised. Growing by a constant instead (m + 4) would rehash far more often and build in O(n²).
Just inserted
Being re-placed
Over threshold
Old table (discarded)