Load factor and rehashing
What you'll learn: You'll learn how to detect when a hash table is getting too crowded and how to automatically expand it to maintain fast performance.
The "Crowded Closet" Problem
Imagine you have a closet with 10 hooks. As you hang more coats, the chances of two coats needing the same hook (a collision) increase. If you hang 20 coats on 10 hooks, every hook is doubled up, and finding your favorite jacket takes twice as long. In a hash table, this "crowdedness" is called the Load Factor.
The Load Factor is a simple ratio: number of items / number of slots. If you have 7 items in a 10-slot table, your load factor is 0.7. As this number approaches 1.0, your hash table slows down because it spends more time resolving collisions than actually finding data.
When to Rehash
To keep operations lightning-fast, we set a threshold—usually a load factor of 0.7 or 0.75. Once the table hits this limit, it’s time to move to a bigger "closet." This process is called Rehashing.
You don't just copy the data; you must:
- Create a new array, typically double the size of the old one.
- Iterate through every item in the old table.
- Run the hash function again for every item based on the new table size.
- Insert the items into their new positions.
Rehashing in C
Here is how the logic looks when checking if it's time to grow:
void insert(HashTable *table, char *key, int value) {
// 1. Calculate current load factor
float load_factor = (float)table->item_count / table->size;
// 2. If it's too crowded (e.g., > 0.7), grow the table
if (load_factor > 0.7) {
resize_and_rehash(table);
}
// 3. Proceed with standard insertion...
int index = hash_function(key, table->size);
// ... add item to table->slots[index]
table->item_count++;
}
Rehashing is computationally expensive because you are re-inserting every single element. However, because it happens infrequently, the average speed of your hash table remains incredibly fast.
Key takeaway
The load factor measures how full a table is, and rehashing is the process of doubling the table size and repositioning all elements to prevent performance-killing collisions.