Sub topic 5
What the load factor measures
This chapter assumes you can read simple Python, know what a hash table (dictionary or map) does, and understand basic Big-O notation. It also assumes you know that a hash table stores entries in an array of buckets and picks a bucket from the key's hash.
The definition
The load factor of a hash table is the number of stored entries divided by the number of buckets.
load factor = size / capacityHere size is the count of key-value pairs currently stored. capacity is the length of the bucket array. The Greek letter alpha (α) is the usual symbol for the load factor in textbooks.
A table with 6 entries and 8 buckets has a load factor of 0.75. A table with 3 entries and 12 buckets has a load factor of 0.25.
The load factor is the average number of entries per bucket. It describes how crowded the table is. It does not say how the entries are distributed. A table with a load factor of 0.75 might have entries spread evenly, or it might have most of them in a few buckets if the hash function is poor.
Computing it in code
The ChainedHashTable class below stores each bucket as a Python list. It exposes the load factor as a method that divides _size by the number of buckets. The put method checks the value after each insert and doubles the capacity when it passes the threshold.
class ChainedHashTable:
def __init__(self, capacity=8, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
def load_factor(self):
return self._size / len(self._buckets)
def _index(self, key):
return hash(key) % len(self._buckets)
def put(self, key, value):
bucket = self._buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self.load_factor() > self._max_load:
self._resize(len(self._buckets) * 2)
def get(self, key, default=None):
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
def _resize(self, new_capacity):
old_buckets = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old_buckets:
for key, value in bucket:
self._buckets[self._index(key)].append((key, value))
table = ChainedHashTable()
for n in range(5):
table.put(f"key{n}", n)
print(table.load_factor())After five inserts into 8 buckets, the program prints 0.625. Note that replacing the value of an existing key returns early. It does not change _size, so the load factor stays the same. Only a new key raises it.
Two things that change it
Two events move the load factor in opposite directions.
- Inserting a new key raises
size, so the load factor goes up. - Resizing to a larger array raises
capacity, so the load factor goes down.
Deleting a key also lowers it. The table's size drops while its capacity stays the same, unless the table shrinks. Shrinking is covered in a later chapter.
Chaining versus open addressing
The meaning of the load factor depends on how the table handles collisions, which are cases where two keys map to the same bucket.
| Strategy | Where entries live | Possible load factor |
|---|---|---|
| Separate chaining | In a list attached to each bucket | Can exceed 1, because a bucket can hold many entries |
| Open addressing | Directly in the array slots | Cannot exceed 1, because each slot holds at most one entry |
With chaining, a load factor of 2.0 means the average chain holds two entries. The table still works, though lookups are slower. With open addressing, a load factor of 1.0 means the array is full and no insert can succeed without a resize.
Common mistakes
- Dividing by the number of non-empty buckets instead of the total capacity. The capacity is the length of the whole array.
- Using integer division. In Python 3,
/gives a float. In languages such as Java or C, dividing two integers truncates the result to 0 unless you convert one operand to a floating-point type first. - Counting deleted slots incorrectly in open addressing. Many implementations leave a marker, often called a tombstone, in a deleted slot. Whether the load factor includes tombstones depends on the implementation, and the choice affects when resizes happen.
The next chapter shows how this one number predicts the number of entries a lookup must examine.
Exercise
A chained hash table has 16 buckets and holds 28 entries. What is its load factor, and is this possible in open addressing?
Show answer
The load factor is 28 / 16 = 1.75. This is possible with chaining, where buckets hold several entries. It is impossible with open addressing, because each slot holds at most one entry, so the load factor cannot exceed 1.
Exercise
A table with 8 buckets and a maximum load factor of 0.75 holds 6 entries. You insert a seventh new key. Does the table resize, and what is the load factor if it doubles?
Show answer
Yes. 7 / 8 = 0.875, which is above 0.75, so the table resizes. After doubling to 16 buckets, the load factor is 7 / 16 = 0.4375.