Hash tables
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A hash table stores key → value pairs and finds a key in O(1) on average. This is how dict in Python, HashMap in Java and symbol tables in compilers are built.
The idea: a hash function turns the key into a number, and the remainder of dividing it by the size of the table gives the number of a "bucket". Different keys can land in the same bucket — that's a collision. The simplest way to deal with them is chaining: each bucket has a linked list.
#define BUCKETS 101
struct entry {
char *key;
int count;
struct entry *next;
};
struct entry *table[BUCKETS];
unsigned hash(const char *s)
{
unsigned h = 5381; // djb2 — a classic hash function
while (*s)
h = h * 33 + (unsigned char)*s++;
return h % BUCKETS;
}
Searching: calculate hash(key), go along the chain in that bucket and compare the keys with strcmp.
When there get to be many more items than buckets, the chains get longer and the table is enlarged (rehash), like realloc for a dynamic array.
Task. Read words until the end of the input and count how often each one appears using a hash table. The last word of the input is the query. Print the number of distinct words (the query counts too) and how many times the query word appeared. The test checks only the answer, but do solve it with a hash table.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.