9.1Hash Functions
String keys: polynomial hashing
Names, usernames, words: most keys are text, not numbers. The division method needs a number, so the text has to be turned into one first. There is a bad way and a good way to do it; the good one is polynomial hashing, which Java's String.hashCode also uses.
- Why adding up character codes gives many collisions
- How polynomial hashing takes the order of the letters into account
- Why the computation is done with Horner's method, taking the mod at each step
1Idea
Every character has a numeric code: 'd' is 100, 'e' 101, 'r' 114, 's' 115. The first idea is to add the codes. But addition ignores the order of the letters: "ders" and "sedr", "abc" and "cba" give the same sum and always land in the same cell. On top of that, the sums of short words stay within a small range.
Polynomial hashing multiplies each letter by a power of a base that depends on its position. With base B = 31 and character codes c0, c1, ..., c(n-1):
h = (c0 · B^(n-1) + c1 · B^(n-2) + ... + c(n-1)) % M
There is no need to compute the powers one by one. Horner's method builds the same sum from left to right: h starts at 0, and at each letter h = h · B + code. Taking % M at every step does not change the result, because working with remainders in addition and multiplication keeps the final remainder the same. This way the number never overflows, even for long strings.
| Text | Sum of codes % 11 | Polynomial hash |
|---|---|---|
| ders | 1 | 8 |
| sedr | 1 | 3 |
| abc | 8 | 5 |
| cba | 8 | 0 |
A small odd prime such as 31 is chosen as the base. Java's String.hashCode uses exactly this formula, except that instead of taking the mod it lets the int overflow wrap around by itself. Python's hash() uses a different method for strings and, for security, may give a different result on every run.
2Step by step
The hash value of the word "ders" is computed. The character codes are under the cells. The base is 31 and M = 11.
- Start with
h = 0. d(100):h = (0 · 31 + 100) % 11 = 1.e(101):h = (1 · 31 + 101) % 11 = 132 % 11 = 0.r(114):h = (0 · 31 + 114) % 11 = 4.s(115):h = (4 · 31 + 115) % 11 = 239 % 11 = 8.- The result is 8. "sedr", with the same letters, gives 3: the order counted.
#define M 11#define BASE 31 int stringHash(const char* text) { int h = 0; for (int i = 0; text[i] != '\0'; i++) { h = (h * BASE + (unsigned char)text[i]) % M; // Horner step } return h;}static final int M = 11;static final int BASE = 31; int stringHash(String text) { int h = 0; for (int i = 0; i < text.length(); i++) { h = (h * BASE + text.charAt(i)) % M; // Horner step } return h;}M = 11BASE = 31 def string_hash(text): h = 0 for c in text: h = (h * BASE + ord(c)) % M # Horner step return hThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Only h is kept.
Taking time proportional to the length is unavoidable; every letter of the key must count. When a hash table is said to be O(1) on average, the length of the key is treated as constant.
4Common mistake
A common mistake is leaving the mod until the end:
for (int i = 0; text[i] != '\0'; i++) h = h * BASE + text[i]; // wrong: int overflows after a few lettersreturn h % M;Powers of 31 grow very fast; after seven or eight letters the int overflows. In C, signed integer overflow is undefined behaviour and h can turn negative, so h % M gives a negative index. Taking % M at every step prevents overflow and does not change the result.
5Try it
With base 31 and M = 11, what is the hash of the string "ab"? ('a' is 97, 'b' is 98)
The answer is B. h = (0 · 31 + 97) % 11 = 9. Then h = (9 · 31 + 98) % 11 = 377 % 11 = 3, because 377 = 34 · 11 + 3.
Show the answer
The answer is B. h = (0 · 31 + 97) % 11 = 9. Then h = (9 · 31 + 98) % 11 = 377 % 11 = 3, because 377 = 34 · 11 + 3.
What does a hash function that adds character codes give for "listen" and "silent"?
The answer is B. Both words are made of the same letters, only in a different order. Addition ignores order, so the sums and the cells are the same. Polynomial hashing multiplies each letter by a different power depending on its position.
Show the answer
The answer is B. Both words are made of the same letters, only in a different order. Addition ignores order, so the sums and the cells are the same. Polynomial hashing multiplies each letter by a different power depending on its position.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.