Data Structures & Algorithms / Module 2: Hashing
Topic 2.3
Load factor and rehashing
When a hash map's drawers count as too full, and why doubling them stays cheap on average.
Watch: when the drawers start filling up, everything moves into a new chest twice the size, and the pile in each drawer gets short again.
- moving now
Like a filing cabinet that keeps filling up
A filing cabinet with 4 drawers is fine for 3 folders. With 30 folders, each drawer holds 7 on average, and finding one means flipping through the drawer. A hash map faces the same thing: the more items per drawer, the longer the chains to check.
So the hash map keeps watching its load factor. When it passes a limit, usually 0.75, it gets a new cabinet with twice as many drawers. Because a drawer number comes from the remainder after dividing by the number of drawers, every item has to be worked out again and moved to its new drawer. Watch the figure: after a rehash, items that were piled up spread out.
Expensive, but rare
One rehash moves every item: O(n). But because the number of drawers always doubles, rehashes get rarer and rarer. Just like a dynamic array, the cost spread over all the inserts stays small, so storing an item is still O(1) on average.
Quiz
A hash map has 16 drawers and 12 items. What is its load factor?
Why does every item have to be worked out again during a rehash?
Why doesn't rehashing make the hash map slow overall?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.