Sub topic 1
A Quick Refresher: Buckets and Index Mapping
Prerequisites
This chapter assumes you can read simple Python and know what a list is. You should know what a dictionary or map does: it stores values under keys and finds them again. You should also know basic Big-O notation, such as the difference between O(1) and O(n). Nothing else is needed. Later chapters build on the vocabulary introduced here.
The Working Model
A hash table stores key-value pairs in an array. Each slot of that array is called a bucket. The number of buckets is the table's capacity. The number of stored pairs is its size.
To find the bucket for a key, the table does two steps:
- Compute a hash code, which is an integer derived from the key. In Python,
hash(key)does this. - Reduce the hash code to a valid position with the remainder operator:
index = hash(key) % capacity.
The result is always between 0 and capacity - 1, so it points at a real bucket. Because the table jumps straight to one bucket instead of scanning every entry, a lookup takes O(1) time on average.
A Minimal Example
The code below shows index mapping on its own. It uses integer keys, because Python hashes small integers to themselves. That makes the arithmetic easy to follow.
capacity = 8
for key in (3, 11, 19, 6):
index = hash(key) % capacity
print(f"key={key:2d} -> bucket {index}")The output is:
key= 3 -> bucket 3
key=11 -> bucket 3
key=19 -> bucket 3
key= 6 -> bucket 6Keys 3, 11 and 19 all land in bucket 3, because each has remainder 3 when divided by 8. Several keys sharing one bucket is a collision. The next chapter explains why collisions cannot be avoided.
Why the Index Depends on Capacity
The index formula uses capacity. If the capacity changes, the same key can map to a different bucket. Take key 11:
| Capacity | Calculation | Bucket |
|---|---|---|
| 8 | 11 % 8 | 3 |
| 16 | 11 % 16 | 11 |
This detail drives the rest of the tutorial. When a table grows, you cannot just copy the old buckets into a bigger array. Each entry has to be placed again using the new capacity. That step is called rehashing.
A Table With Buckets
Here is a small table class. It stores each bucket as a list of (key, value) pairs. It shows the structure without handling resizing yet.
class SimpleTable:
def __init__(self, capacity=8):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
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
def get(self, key, default=None):
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
table = SimpleTable()
table.put(3, "a")
table.put(11, "b")
print(table.get(11))
print(len(table._buckets[3]))This prints b and then 2, because keys 3 and 11 share bucket 3.
Notice that put compares keys with == after finding the bucket. The hash only narrows the search to one bucket. Equality picks the right entry inside it.
Common Errors
- Using the hash code directly as an index. Hash codes can be huge or negative. Always reduce them to the capacity range first. In Python,
%returns a non-negative result for a positive capacity. - Assuming the index is permanent. The index depends on the capacity, so it is only valid until the next resize.
- Skipping the equality check. Two different keys can share a bucket, so matching on bucket alone returns wrong values.
Exercise
A table has capacity 8 and holds integer keys. Which bucket does key 21 map to? What bucket does it map to after the capacity becomes 16?
Show answer
With capacity 8, 21 % 8 = 5, so bucket 5. With capacity 16, 21 % 16 = 5, so it stays in bucket 5. Key 21 happens not to move, but key 13 (13 % 8 = 5, 13 % 16 = 13) would move. Every entry still has to be recomputed, because you cannot tell in advance which ones change.