Sub topic 6
Bad hashes: summing characters and other traps
This chapter assumes you have read the earlier chapters of this tutorial on determinism, uniformity, and mapping a hash value to a bucket. It also assumes you can read Python, binary, XOR, and the modulo operator. Here you will take five hash functions that look reasonable and see how each one fails. By the end you should be able to spot the same mistakes in code you review.
Why study bad hashes
A hash function can be deterministic and fast and still be useless. Determinism only means the same input gives the same output. A function that returns 0 for everything is deterministic and very fast. The failures worth learning are the ones that look plausible, because those ship.
A bad hash does not usually produce wrong answers. A hash table built on one still returns the correct values. It just gets slow, because many keys pile into few buckets and lookups degrade toward a linear scan. The bug shows up as latency, not as an exception.
Trap 1: summing character codes
The first idea most people try is to add up the byte values of the string:
from collections import Counter
from itertools import permutations
def sum_hash(s, buckets):
return sum(s.encode()) % buckets
def first_byte_hash(s, buckets):
return s.encode()[0] % buckets
def load_profile(hash_fn, keys, buckets):
counts = Counter(hash_fn(k, buckets) for k in keys)
return len(counts), max(counts.values())
anagrams = ["".join(p) for p in permutations("listen")]
print(len(anagrams))
print(load_profile(sum_hash, anagrams, 16))
print(load_profile(first_byte_hash, anagrams, 16))load_profile returns two numbers: how many buckets received at least one key, and how many keys landed in the fullest bucket. The output is:
720
(1, 720)
(6, 120)All 720 rearrangements of "listen" are different strings, yet the sum hash puts every one of them in the same bucket. Addition is commutative, so the hash cannot see letter order. The sum of the bytes in "listen" is 655, and 655 % 16 is 15 for every permutation.
The first-byte hash is also poor. It sees only six distinct values, because only the first letter matters. Real data makes this worse. Many words share a prefix, and many keys share a format such as user_1042, user_1043, or 2026-12-03.
Summing has a second flaw that has nothing to do with order. The sums bunch together in a narrow range. A five-letter lowercase word has a byte sum between 5 × 97 = 485 and 5 × 122 = 610. That is only 126 possible values. A table with 1024 buckets can therefore use at most 126 of them, and most of those get few keys. Short keys make this worse, because the sum cannot spread across a wide range of values.
Trap 2: combining fields with XOR
When a key has several parts, such as a coordinate pair (x, y), a tempting shortcut is to XOR the parts together:
def xor_hash(x, y):
return x ^ y
print(xor_hash(3, 5), xor_hash(5, 3))
print([xor_hash(i, i) for i in range(5)])The output is:
6 6
[0, 0, 0, 0, 0]XOR is symmetric, so (3, 5) and (5, 3) always collide. Any pair with equal parts hashes to 0. On a grid, the whole diagonal ends up in one bucket. Many other pairs also share a hash: (1, 2), (2, 1), and (0, 3) all give 3. A good combiner must make position matter. Multiplying by a constant before mixing, as a polynomial hash does, achieves that.
Trap 3: keys with a pattern and a bucket count that matches it
Sometimes the hash is the identity function, and the keys have structure. Memory addresses, record IDs allocated in blocks, and timestamps rounded to a boundary are typical examples. Suppose every key is a multiple of 16:
keys = range(0, 1600, 16)
print({k % 16 for k in keys})
print(len({k % 17 for k in keys}))The output is:
{0}
17With 16 buckets, all 100 keys go to bucket 0. With 17 buckets, they cover every bucket. The cause is arithmetic: k % 16 keeps only the low four bits, and those bits are always zero for multiples of 16. Any power-of-two bucket count looks only at the low bits of the hash. Any structure in those bits becomes clustering.
A prime bucket count hides this particular problem, but it does not make the hash good. If the hash function mixes poorly, a prime modulus only covers up part of the damage. The better fix is a hash whose low bits depend on every input bit. The next chapter builds such hashes.
The polynomial hash from the earlier examples has a milder version of this problem. With base 31 and 16 buckets, 31 is congruent to −1 modulo 16. The bucket index is then an alternating sum of the bytes mod 16. It is better than the plain sum, because it separates anagrams by which letters sit at even positions. It still uses only a thin slice of the information in the string. A base and a bucket count that share structure are a quiet source of clustering.
Trap 4: a hash that is not stable
Python's built-in hash() on strings is randomized per process. Run print(hash("hello")) twice and you get two different numbers. This protects dictionaries against attack, which a later chapter covers. It breaks any code that uses hash() to decide where data lives outside the running process. Examples are sharding keys across servers, naming cache files, and storing a hash in a database. Two runs would disagree about where a key belongs.
Determinism has a scope: the same input must give the same output wherever you rely on the value. For a persisted or shared value, use a hash you control, such as hashlib or your own implementation, instead of hash().
The reverse mistake also exists. A hash that depends on something other than the key's content breaks equality. Hashing a mutable object by its memory address means two equal objects land in different buckets. If two keys compare equal, they must hash equal. If you change how equality works, change the hash with it.
Trap 5: throwing away input
Any hash that ignores part of the key wastes that part. Common examples:
- Hashing only the first or last few characters of a string.
- Hashing only the length of the key.
- Truncating a 64-bit value to 8 bits before mixing it, instead of after.
- Hashing a floating-point number by its integer part only.
Each of these makes keys that differ in the ignored part collide on purpose. The rule is that every input bit should be able to influence the output, and the mixing should happen before you reduce to a bucket index.
Summary of the traps
| Trap | Why it fails | Symptom | Direction of the fix |
|---|---|---|---|
| Sum of bytes | Order is ignored, range is narrow | Anagrams collide, few buckets used | Make position matter, for example multiply before adding |
| First byte or length only | Most of the key is ignored | Few distinct values | Use every byte |
| XOR of fields | XOR is symmetric and `x ^ x` is 0 | `(a, b)` and `(b, a)` collide, diagonals pile up | Mix each field with a multiply or shift first |
| Pattern plus power-of-two modulo | Low bits carry the pattern | One bucket holds everything | Mix high bits into low bits |
| Unstable hash | Value changes between runs or machines | Data lands in the wrong place after restart | Use a defined algorithm |
How a bad hash becomes a slow program
A well-behaved table does constant work per lookup on average. With the sum hash on the 720 anagrams, a lookup for the last key scans up to 720 entries. At a million keys, the same clustering means a million comparisons per lookup. The data structure stays correct and loses its main benefit.
A quick review checklist
When you read a hash function, ask these questions in order:
- Does swapping two parts of the key change the hash? If not, order is lost.
- Does every byte or field of the key affect the result?
- How many distinct outputs are possible for your real keys, not for all possible keys?
- What happens to keys that share a pattern, such as multiples of 16 or a common prefix?
- Is the value stable everywhere you rely on it?
You can answer most of these by running a load_profile style test on realistic data. Test with the keys your program will see, not with random strings, because random data hides patterns.
Exercise
A table has 8 buckets and uses k % 8 as its hash. The keys are the even numbers 0, 2, 4, ..., 98. How many of the 8 buckets get used, and what is the fix that does not require changing the bucket count?
Show answer
Only 4 buckets are used (0, 2, 4, 6), because even numbers always have a low bit of 0, so k % 8 can never be odd. The other four buckets stay empty and each used bucket holds about 12 or 13 keys. The fix is to mix the key before reducing it, so that high bits and the low bit are combined into the low bits, for example by multiplying by an odd constant and then using the high bits or XOR-ing a shifted copy of the value into itself.
Exercise
Why do (3, 5) and (5, 3) get the same hash under x ^ y, and name one change that makes the order matter.
Show answer
XOR is commutative, so swapping the operands gives the same result. Multiply one field by an odd constant before combining, for example (x * 31) ^ y or x * 31 + y. Then (3, 5) gives a different value than (5, 3).