A hash function maps a key from a huge domain, such as every possible country name, into the small range of indexes of an array. These notes build one for strings step by step, show it in C++, and give you three tools to try it yourself.
Suppose we want to look up a country's capital instantly. There are 194 countries in our list, so an array of a few hundred slots is plenty. But an array is indexed by integers 0 to M − 1, and our keys are strings like "Italy".
A hash function solves this in two steps:
mod M.The result is the slot where ("Italy", "Rome") is stored. To look Italy up later, we compute the same hash and go straight to that slot, with no searching.
The simplest idea, adding up the character codes, is a poor one: "CAB", "ABC" and "BCA" all get the same sum. The polynomial rolling hash gives each position its own weight, a power of a constant A. With A = 31:
Here ci is the code of the character at position i, counting from 0.
Two choices of letter value are common. Hand examples often use a = 1, b = 2, …, z = 26. The C++ code uses the character's ASCII code, so 'A' = 65, 'B' = 66, 'C' = 67.
| Position i | Letter | 31i | Value (a=1) | Term | ASCII code | Term |
|---|---|---|---|---|---|---|
| 0 | C | 1 | 3 | 3 | 67 | 67 |
| 1 | A | 31 | 1 | 31 | 65 | 2,015 |
| 2 | B | 961 | 2 | 1,922 | 66 | 63,426 |
| Hash | 1,956 | 65,508 |
The hash is far too big to be an index, so we keep only the remainder after dividing by the table size M:
With M = 250: the a = 1 version gives 1956 mod 250 = 206, and the ASCII version that the C++ computes gives 65508 mod 250 = 8. Either is fine, as long as the same function is used every time.
The exact hash grows very fast: each character multiplies the weight by 31, so a 13-letter word already has a hash of about 20 digits, more than a long long can hold. The code therefore takes % HASH_TABLE_SIZE at every step, so the numbers stay small no matter how long the word is:
#include <iostream>
#include <string>
using namespace std;
const int PRIME_CONST = 31;
const int HASH_TABLE_SIZE = 250;
// Polynomial rolling hash, reduced mod HASH_TABLE_SIZE at every step.
int hashFunction(const string& key) {
long long hashCode = 0;
long long power = 1; // 31^i mod HASH_TABLE_SIZE
for (unsigned char ch : key) {
hashCode = (hashCode + ch * power) % HASH_TABLE_SIZE;
power = (power * PRIME_CONST) % HASH_TABLE_SIZE;
}
return hashCode; // always 0 .. HASH_TABLE_SIZE - 1
}
int main() {
string key;
cout << "Enter word (or 'quit' to exit): ";
while (getline(cin, key) && key != "quit") {
int index = hashFunction(key);
cout << "Word \"" << key << "\" maps to index: " << index << endl;
cout << "Enter word (or 'quit' to exit): ";
}
return 0;
}
hashCode and power are below 250, so the biggest product, ch * power, is under 255 × 250 = 63,750.unsigned char because a plain char can be negative for accented letters such as é.(a + b) mod M and (a · b) mod M can be computed from a mod M and b mod M, so reducing early never changes the index. In the tool above, the two "mod" columns of the table are exactly what this code computes, step by step.The hashFunc in the hash table class (section 6) works the same way.
31 · x equals (x << 5) − x. Java's String.hashCode uses the same constant.Two different keys landing in the same slot is a collision. With more keys than slots it is unavoidable, and even with plenty of room some collisions are expected. The tool below compares three hash functions on the full country list.
The class's HashTable stores (country, capital) pairs in an array. put hashes the country and stores the pair in that slot. If the slot is taken by another country (a collision), it tries the next slot, and the next, until it finds an empty one. This is called linear probing. get follows the same path: it starts at the hashed slot and steps forward until it finds the key or reaches an empty slot, which means the key is not in the table.