Sub topic 2
From Hash Value to Bucket Index
Assume you know basic Python, hexadecimal and binary notation, bitwise XOR, modulo, and dictionary-like maps. A hash table uses a hash function to turn a key into a fixed-size integer. It then maps that integer to one of its buckets:
bucket = hash_value % bucket_countFor example, hash value 73 maps to bucket 9 when there are 16 buckets. The modulo operation keeps the index in the valid range 0 through bucket_count - 1.
flowchart TD
A[Input key] --> B[Hash function]
B --> C[Fixed-size hash value]
C --> D[Modulo bucket count]
D --> E[Bucket index]A good hash distributes unrelated keys across buckets. Poor distribution creates long collision chains, which make lookup slower.
Bad hashes: summing characters and other traps
A tempting design is to add the character codes:
def sum_hash(text: str, buckets: int) -> int:
return sum(text.encode()) % bucketsThis ignores character order. The strings listen and silent produce the same sum even though their letters appear in different positions. Repeated patterns, similar prefixes, and limited input ranges can also concentrate values in a few buckets.
A hash should be deterministic, so the same key must always produce the same value during the operation that uses it. It should also be fast and approximately uniform.
Building a better hash
Polynomial hashing makes position matter. Each new byte shifts the previous contribution before adding the next byte. FNV-1a uses XOR and multiplication by a prime:
def polynomial_hash(data: bytes, buckets: int, base: int = 31) -> int:
value = 0
for byte in data:
value = (value * base + byte) & 0xFFFFFFFF
return value % buckets
def fnv1a_32(data: bytes, buckets: int) -> int:
value = 0x811C9DC5
for byte in data:
value ^= byte
value = (value * 0x01000193) & 0xFFFFFFFF
return value % buckets
words = [b"listen", b"silent"]
print([fnv1a_32(word, 16) for word in words])These are suitable examples of non-cryptographic hashes, not replacements for password hashing or authentication.
Measuring the avalanche effect
The avalanche effect means that a small input change changes many output bits. Flip one input bit, hash both inputs, and count differing output bits. A strong cryptographic hash changes about half of its output bits on average.
How likely is a collision? The birthday bound
Collisions are unavoidable because many possible inputs map into a finite set of outputs. For n inputs and m possible hash values, the approximate collision probability is:
1 - exp(-n(n - 1) / (2m))A 32-bit hash has about a 50% chance of at least one collision after roughly 77,000 random inputs. This is why hash width and input volume matter.
Exercise
Why does summing character codes make an especially poor hash for words?
Show answer
It ignores character order, so anagrams receive the same value and can cluster in the same buckets.