Lesson 2 · Unit 04
Load factor and resizing
Why tables double, and what "amortised O(1)" is promising
What you practise
- Doubling and rehashing
- Amortised O(1), worst case O(n)
Try a question from this lesson
Pick one
A hash table has 8 buckets and never grows. You insert 8,000 keys, spread evenly. About how many pairs does one lookup scan?
Correct answer
1,000
Why
8,000 keys over 8 buckets is 1,000 per chain, and a lookup scans its chain. The table still works, but it is now eight slow lists. To stay fast, the number of buckets has to grow with the data.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Load factor
The load factor is the number of items divided by the number of buckets. It is the average chain length.
Keep it under a threshold (0.75 is a common choice) and chains stay short, so lookups stay O(1). When an insert pushes it over the threshold, the table grows.
Concept
Doubling keeps resizes rare
A resize costs O(n), which sounds bad for an insert. But after doubling to 2n buckets, about n more inserts fit before the next resize.
So every expensive resize is paid for by the many cheap inserts before it. Averaged over a long run, an insert costs O(1): amortised constant time. One unlucky insert still pays O(n).
10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.