Sub topic 18
Designing Hash Functions
This chapter assumes you know what a hash table is, what a collision is, and how modular arithmetic works. You should also be comfortable with powers of two and with reading short Python. The chapter covers what makes a hash function good, the division and multiplication methods, and the mistakes that GATE questions like to test.
What a Hash Function Must Do
A hash function h maps a key k from a large universe U to a slot number in the range 0 to m-1, where m is the table size. A good hash function has three properties:
- Deterministic. The same key always gives the same slot. Without this, a stored key cannot be found again.
- Fast. It should take O(1) time for keys of fixed size.
- Uniform. Each slot should be about equally likely to receive a key. This is the simple uniform hashing assumption (SUHA): each key is equally likely to hash to any of the m slots, independently of the other keys.
Uniformity is the hard part. A function that sends every key to slot 0 is deterministic and fast, but it turns the table into a linked list with O(n) search.
Collisions cannot be avoided when |U| > m, because of the pigeonhole principle. Two keys must share a slot for some inputs. Design aims to make collisions rare and spread evenly, not to remove them.
Keys That Are Not Integers
Hash functions in textbooks assume integer keys. Strings and other objects must first be turned into integers. A common way to do this for a string is to treat its characters as digits in some base:
def string_to_int(s, base=31):
value = 0
for ch in s:
value = value * base + ord(ch)
return value
print(string_to_int("cat"))
print(string_to_int("act"))The two strings are anagrams, but they give different integers. A weaker scheme that only adds the character codes would give the same value for both, and every anagram of a word would collide. Weighting each position by a power of the base avoids this.
The Division Method
The division method is:
h(k) = k mod m
It needs one division and is very fast. The choice of m matters a great deal.
- Avoid m = 2^p. Then k mod m is just the lowest p bits of k. If keys share a pattern in those bits, many keys fall into few slots. For example, if every key is even and m = 8, only slots 0, 2, 4, and 6 are ever used, so half the table is wasted.
- Avoid m = 10^p for decimal keys, for the same reason: only the last p digits count.
- Prefer m to be a prime that is not close to a power of 2 or 10. A prime shares no factor with typical key patterns, so the remainders spread out.
def division_hash(k, m):
return k % m
keys = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
for m in (8, 11):
slots = sorted({division_hash(k, m) for k in keys})
print(m, slots)The keys are all multiples of 4. With m = 8 they land in only two slots, 0 and 4. With m = 11 they use ten different slots.
The Multiplication Method
The multiplication method has two steps. Pick a constant A with 0 < A < 1. Then:
- Compute k·A and keep only its fractional part, written {k·A} = k·A − floor(k·A).
- Multiply by m and take the floor.
So h(k) = floor(m · {k·A}).
The value of m is not critical here. A power of two works well, because the final step becomes a bit shift. Knuth suggests A ≈ (√5 − 1)/2 ≈ 0.6180339887, which tends to spread keys evenly.
import math
def multiplication_hash(k, m, A=(math.sqrt(5) - 1) / 2):
frac = (k * A) % 1
return math.floor(m * frac)
m = 16
for k in (1, 2, 3, 4, 5, 6):
print(k, multiplication_hash(k, m))Consecutive keys land far apart, in slots 9, 3, 12, 6, 0, and 10. This is useful when real keys are often sequential, such as IDs 1001, 1002, 1003.
Here is a worked example with exact numbers. Take k = 123, m = 100, and A = 0.6180339887.
- k·A = 123 × 0.6180339887 = 76.0181806...
- The fractional part is 0.0181806...
- m × 0.0181806 = 1.81806..., and its floor is 1.
So h(123) = 1.
Comparing the two methods
| Property | Division method | Multiplication method |
|---|---|---|
| Formula | k mod m | floor(m · {k·A}) |
| Best table size | Prime, away from powers of 2 | Any, often a power of 2 |
| Speed | One division | One multiplication and a shift |
| Sensitivity to m | High | Low |
| Needs a constant | No | Yes (A) |
Other Practical Ideas
- Folding. Split a long key into parts and add them. For example, split the phone number 5551234 into 555 and 1234, giving 555 + 1234 = 1789, and then apply mod m.
- Mid-square. Square the key and take the middle digits. Middle digits depend on every digit of the key, so they mix well.
- Universal hashing. Pick the function at random from a family when the program starts, for example h(k) = ((a·k + b) mod p) mod m, where p is a prime larger than every key, a is chosen from 1 to p−1, and b from 0 to p−1. No fixed set of keys is bad for every run, so an adversary cannot plan collisions in advance. For any two distinct keys, the chance of a collision is at most 1/m.
import random
def make_universal_hash(m, p=1_000_003):
a = random.randint(1, p - 1)
b = random.randint(0, p - 1)
return lambda k: ((a * k + b) % p) % m
h = make_universal_hash(11)
print([h(k) for k in range(5)])The output differs from run to run, which is the point.
Common Errors
- Using a power of two with the division method on keys that share low bits.
- Hashing a negative or large key without taking care. Python's
%returns a non-negative result for a positive m, but in C or Javak % mcan be negative. Always check the sign. - Changing the function after inserting keys. If h or m changes, existing keys are in the wrong slots. Resizing a table means rehashing every key.
- Using a function that ignores part of the key. Hashing only the first letter of a name sends all names starting with "S" to one slot.
- Assuming a good function removes collisions. It only spreads them. Collision handling, covered in the following chapters, is still needed.
How Design Affects Cost
The expected cost of a search depends on the load factor α = n/m, which later chapters analyze. That analysis assumes SUHA. A poor hash function breaks the assumption. Then the cost can reach O(n) even when α is small, because the keys pile into a few slots. Good design is what makes the O(1) average cost real.
Exercise
A table has m = 12 slots and uses h(k) = k mod 12. The keys inserted are 12, 24, 36, 48, 60, and 72. How many distinct slots are used, and what change to m would fix the problem?
Show answer
All six keys are multiples of 12, so each gives remainder 0. Only one slot (slot 0) is used. Changing m to a prime such as 13 spreads them: 12, 11, 10, 9, 8, 7 are the slots, six distinct values.
Exercise
Using the multiplication method with m = 100 and A = 0.6180339887, compute h(123). Show the steps.
Show answer
123 × 0.6180339887 = 76.0181806..., so the fractional part is 0.0181806.... Multiply by 100 to get 1.81806..., and the floor is 1. So h(123) = 1.
Exercise
Why does adding the character codes of a string give a worse hash than treating the characters as digits in base 31?
Show answer
Adding the codes ignores order, so all anagrams of a word get the same value and collide. Using base-31 weights makes each position contribute differently, so "cat" and "act" give different values.