Sub topic 4
From hash value to bucket index
A hash function turns a key into a large integer. The table's array has only a few slots, so the table needs one more step: reduce that integer to a valid position in the array. This chapter covers that step, why the way you do it matters, and what changes when the table grows.
This chapter assumes you know how a hash function produces an integer, how array indexing by position works, and what the modulo operator (%) and bitwise AND (&) do on integers.
The reduction step
A bucket is one slot of the table's underlying array. If the array has capacity buckets, valid indexes run from 0 to capacity - 1. The reduction takes any integer hash h and maps it into that range.
The hash function and the reduction are separate jobs. The hash function should spread distinct keys across the full integer range. The reduction only has to fit the result into the array. Keeping them separate lets the table change its capacity without changing the keys' hashes.
Reduction by modulo
The simplest reduction is the remainder after division:
index = h % capacityFor any positive capacity, the result is between 0 and capacity - 1. Equal hashes always give equal indexes, as long as the capacity has not changed.
Your chapter's earlier code, hash(key) % len(self._buckets), does exactly this. It works with any capacity, such as 10, 12, or 97.
Negative hash values
In Python, % with a positive divisor always returns a non-negative result, so -7 % 8 is 1. Many other languages differ. In Java and C, -7 % 8 is -7, which is not a valid array index. If you port a hash table to those languages, you have three options:
- Use a floor-modulo function such as Java's
Math.floorMod. - Clear the sign bit first, for example
(h & 0x7fffffff) % capacity. - Use a bitmask (below), which never produces a negative result.
Do not use Math.abs(h) % capacity in Java. Math.abs(Integer.MIN_VALUE) is still negative.
Reduction by bitmask
Division is slower than a bitwise AND on most hardware. If the capacity is a power of two, the remainder is just the low bits of h, and you can compute it with a mask:
index = h & (capacity - 1)For capacity = 8, capacity - 1 is 0b111, so the mask keeps the lowest three bits. This code compares the two approaches:
def index_mod(h, capacity):
return h % capacity
def index_mask(h, capacity):
return h & (capacity - 1) # capacity must be a power of two
for h in [0, 5, 13, 27, 1000003, -7]:
print(h, index_mod(h, 8), index_mask(h, 8))Both columns agree for every value, including -7, because Python integers behave as if they have infinitely many sign bits.
The mask only works when the capacity is a power of two. This is why many implementations, including Python's dict and Java's HashMap, grow by doubling.
Why the low bits matter
Both reductions depend heavily on the low bits of h. A mask uses nothing else. A modulo by a power of two also uses nothing else. If the hash values share a pattern in their low bits, many keys land in the same bucket even though the full hash values differ.
Here is an example where every hash is a multiple of 16:
hashes = [i * 16 for i in range(32)]
def load(hashes, capacity):
counts = [0] * capacity
for h in hashes:
counts[h % capacity] += 1
return counts
print(load(hashes, 8))
print(load(hashes, 7))The output is:
[32, 0, 0, 0, 0, 0, 0, 0]
[5, 4, 5, 4, 5, 4, 5]With capacity 8, all 32 keys fall into bucket 0, because every multiple of 16 is also a multiple of 8. With capacity 7, the keys spread almost evenly. Because 7 shares no factor with 16, the multiples of 16 cycle through all residues.
This kind of pattern is common in real data. Memory addresses are often multiples of 8 or 16. Integer IDs may step by a fixed amount. Integer hashes that are the number itself, as in CPython, inherit these patterns.
Strategies for protecting the index
There are three common defenses. Each trades something.
| Strategy | How it works | Cost |
|---|---|---|
| Prime capacity with modulo | Pick a prime size, so strided patterns do not share factors with the capacity | A division per lookup, and resizing must find the next prime |
| Power-of-two capacity with a mixing step | Scramble the bits of `h` before masking, so high bits influence the low bits | A few extra bit operations per lookup |
| Strong hash function | Make the hash itself well distributed in every bit | More work per key, especially for long strings |
Java's HashMap uses the second approach. It computes h ^ (h >>> 16) before masking, which folds the upper 16 bits into the lower 16. This is cheap, and it protects against hashes that differ only in their high bits. CPython's open-addressing dict takes a related approach. Its probe sequence feeds the upper bits of the hash into later probes, so those bits still matter after a collision.
The index depends on the capacity
The bucket index is not a property of the key alone. It is a function of the key and the current capacity. When a table resizes, every entry's index may change, so each entry has to be reinserted. This is why _resize in the chaining table calls _index(k) again for every pair instead of copying the buckets.
With power-of-two capacities and a mask, the change has a simple structure. When capacity doubles from old to new = 2 * old, the new mask has one more bit. An entry's new index is either its old index or its old index plus old:
old, new = 8, 16
for h in [5, 13, 21, 29]:
print(h, h & (old - 1), h & (new - 1))This prints 5 5 5, 13 5 13, 21 5 5 and 29 5 13. All four hashes share old index 5. After doubling, two stay at 5 and two move to 13, which is 5 + 8. Each old bucket splits cleanly into two new buckets, and some implementations use this to resize without recomputing full hashes.
Practical rules
- Compute the full hash once per operation, then reduce it. Do not hash the key again inside each loop iteration of a probe sequence.
- Treat the reduction as part of the table, not the key class. A key's
__hash__should not know about capacity. - If you use a mask, assert that the capacity is a power of two when the table is created and when it resizes.
- If you use modulo in a language where
%can be negative, normalize the result before indexing. - Test with structured keys, such as multiples of 16 or 1024 and sequential IDs. Random-looking test keys hide weak reductions.
Summary
The reduction step maps a large hash integer to an array position. Modulo works for any capacity. A bitmask is faster but requires a power-of-two capacity and uses only the low bits. Because low bits can carry patterns, tables pair the mask with a bit-mixing step or use a prime capacity. Because the index depends on the capacity, a resize recomputes it for every entry.
Exercise
A table has capacity 16 and uses a bitmask. A key's hash is 100. What is its bucket index? If the table doubles to 32, what is the new index?
Show answer
Use h & (capacity - 1). 100 is 0b1100100. With mask 15 (0b1111), the low four bits are 0100, so the index is 4. With mask 31 (0b11111), the low five bits are 00100, so the index is 4. The entry stays in bucket 4, because bit 4 of 100 is 0.
Exercise
Why does a table with capacity 12 and the index h & 11 perform badly, even if the hash function is perfect?
Show answer
The mask 11 is 0b1011, so bit 2 of the result is always 0. Only indexes 0 to 3 and 8 to 11 can occur. Buckets 4 to 7 are never used, so the same keys crowd into 8 of the 12 buckets. A bitmask requires a power-of-two capacity, so that capacity - 1 has all low bits set.