Sub topic 5
From hash value to bucket index
A hash function returns a large integer, such as 32 or 64 bits. A hash table has a small number of buckets, such as 16 or 1024. This chapter covers the step between them: reducing a hash value to a bucket index. This step can make a good hash behave badly.
This chapter assumes you know the modulo operator, bitwise AND and shifts, and how a dictionary stores entries in an array of buckets. It also assumes you have a hash function that returns an integer, such as the FNV-1a function from an earlier chapter.
The two-step pipeline
A table lookup does two separate jobs:
- Hash the key to a fixed-width integer. This is the hash function's job.
- Reduce that integer to a number in the range
0ton - 1, wherenis the number of buckets.
The hash function can be excellent and the table can still perform poorly if step 2 throws away the good bits. The rest of this chapter looks at the common ways to do step 2 and how each one fails.
Reduction by modulo
The simplest reduction is h % n. It works for any table size, and the result is always in range.
Two details matter in practice:
- Negative values. In Python,
-7 % 4is1, because the result takes the sign of the divisor. In C, C++, and Java,-7 % 4is-3, which is not a valid index. Java offersMath.floorMod. In C, use an unsigned hash type. - Cost. Integer division is slower than most other operations on a CPU. For a table that does millions of lookups, this adds up.
Modulo bias
If the hash range is not a multiple of n, some buckets receive one extra hash value. Take a tiny 4-bit hash with 10 buckets:
from collections import Counter
counts = Counter(h % 10 for h in range(16))
print(sorted(counts.items()))This prints [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 1), (7, 1), (8, 1), (9, 1)]. Buckets 0 to 5 are twice as likely as buckets 6 to 9. With a 32-bit hash and 10 buckets, six buckets get one extra value out of about 429 million each. That difference is far too small to matter for a hash table, so bias only matters when the hash range is small compared with n. It matters more for tasks such as picking a random number from random bytes.
Reduction by mask
When n is a power of two, h % n equals h & (n - 1). A mask is a single cheap instruction, so many implementations (Java's HashMap, many C++ and Rust tables) keep the bucket count at a power of two and mask.
The cost is that a mask keeps only the lowest bits of the hash. Any weakness in those bits goes straight into the table. Consider keys that are all multiples of 16, such as memory addresses of 16-byte-aligned objects:
from collections import Counter
keys = [i * 16 for i in range(1, 33)]
print(sorted(Counter(k & 15 for k in keys).items()))
print(len(Counter(k % 17 for k in keys)))The first line prints [(0, 32)]. All 32 keys land in bucket 0 of a 16-bucket table, so lookups become a linear scan of one chain. The second line prints 17, because 17 is prime and shares no factor with 16, so the keys spread over every bucket.
This is the traditional argument for prime table sizes: a prime modulus mixes in every bit of the hash, so patterns in the keys rarely line up with n. Primes have a cost, though. They need a division, and growing the table means finding the next prime.
Mixing the bits first
You can keep power-of-two sizes and still be safe if the hash value has good bits everywhere. There are two ways to get that.
- Use a hash with strong avalanche behavior, so every output bit depends on every input bit. Then the low bits are as good as any others.
- Apply a cheap mixing step after hashing. Multiplicative hashing (Fibonacci hashing) multiplies by a large odd constant derived from the golden ratio and then keeps the high bits, which depend on the whole product:
def fib_bucket(h: int, bits: int) -> int:
"""Map a hash to one of 2**bits buckets using the high bits of a 64-bit product."""
return ((h * 0x9E3779B97F4A7C15) & 0xFFFFFFFFFFFFFFFF) >> (64 - bits)
keys = [i * 16 for i in range(1, 33)]
from collections import Counter
counts = Counter(fib_bucket(k, 4) for k in keys)
print(sorted(counts.items()))The keys that all collapsed into bucket 0 under a mask now spread across the 16 buckets. The exact counts depend on the constant, but no bucket comes close to holding all 32 keys.
Multiply-shift for any size
For a 32-bit hash h and any bucket count n, (h * n) >> 32 scales the hash range down to 0..n-1 without a division. It is sometimes called "fast range". Like Fibonacci hashing, it uses the high bits of the hash, so it needs a hash whose high bits are good.
def fast_range32(h: int, n: int) -> int:
return (h * n) >> 32
print(fast_range32(0, 10), fast_range32(2**32 - 1, 10), fast_range32(2**31, 10))This prints 0 9 5: the smallest hash maps to the first bucket, the largest to the last, and the midpoint to the middle.
Comparing the methods
| Method | Table size | Uses which bits | Main risk |
|---|---|---|---|
| `h % n` | Any, ideally prime | All bits | Slow division. Small bias if the hash range is small. |
| `h & (n - 1)` | Power of two | Low bits only | Patterned keys or weak low bits cause clustering. |
| Fibonacci (multiply, keep high bits) | Power of two | High bits of the product | Constant must be odd and well chosen. |
| `(h * n) >> 32` | Any | High bits | Needs good high bits in `h`. |
Resizing and why you store the full hash
A table's load factor is the number of items divided by the number of buckets. As it rises, chains get longer. Most tables grow when the load factor passes a threshold such as 0.75, usually by doubling the bucket count.
Changing n changes every item's index, so every item must be moved. That is why tables commonly store each key's full hash next to the entry. During a resize, the table reuses the stored value instead of rehashing the key, which could be expensive for long strings. The stored hash also lets a lookup compare two integers before it compares the keys themselves.
class ChainedTable:
def __init__(self, size=8):
self.buckets = [[] for _ in range(size)]
self.count = 0
def _index(self, h):
return h & (len(self.buckets) - 1)
def put(self, key, value):
h = hash(key)
chain = self.buckets[self._index(h)]
for i, (stored_h, stored_key, _) in enumerate(chain):
if stored_h == h and stored_key == key:
chain[i] = (h, key, value)
return
chain.append((h, key, value))
self.count += 1
if self.count > 0.75 * len(self.buckets):
self._grow()
def _grow(self):
old = self.buckets
self.buckets = [[] for _ in range(2 * len(old))]
for chain in old:
for entry in chain:
self.buckets[self._index(entry[0])].append(entry)
t = ChainedTable()
for i in range(100):
t.put(i, i)
print(len(t.buckets), t.count)This prints 256 100. The table grew from 8 buckets to 256 as items arrived, and _grow never called hash again. Python masks negative hash values correctly, because & on a negative integer behaves as two's complement.
Common mistakes
- Masking a hash with weak low bits. The sum-of-characters hash is an example. Check the low bits of your hash before you pair it with a mask, or mix first.
- Assuming a prime size fixes a bad hash. A prime modulus hides some patterns, but a hash that maps many keys to the same value still collides in every bucket.
- Using
%with a signed hash in C-family languages. A negative result indexes outside the array. - Forgetting to re-bucket on resize. Copying entries to the same positions in a bigger array makes lookups miss.
- Persisting bucket indexes. An index depends on
n, and with randomized hashing it also depends on the seed. Store keys or full hashes, not indexes.
Exercise
A table has 8 buckets and uses h & 7. Keys arrive with hash values 0, 8, 16, 24, 32, 40, 48 and 56. Which buckets do they occupy, and what are two ways to fix the problem without changing the key set?
Show answer
All eight keys land in bucket 0, because the low three bits of every hash value are zero. One fix is to use a prime number of buckets, such as 11, so the modulus does not share a factor with 8. The other is to mix the bits before reducing, for example with Fibonacci hashing, which keeps the high bits of the product so all input bits affect the index.
Exercise
Why does a table that stores the full hash of each entry resize faster than one that stores only keys and values?
Show answer
During a resize, every entry needs a new index for the larger bucket array. With the full hash stored, the table computes the new index from that stored value. Without it, the table must hash every key again, which costs time proportional to key length and may involve user-defined code.