Hash Table
Count words with separate chaining and unordered_map.
What is Hash Table?
A hash function maps a key to a bucket; collisions require a strategy such as chaining or open addressing.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
See how it works
Type a key and store or look it up. The key is hashed to a bucket number, so the program jumps straight to the right bucket.
C and C++ code examples
#include <stdio.h>
#include <string.h>
typedef struct Item {
const char *key;
int count;
struct Item *next;
} Item;
unsigned hash(const char *text) {
unsigned value = 5381;
while (*text) {
value = value * 33u ^ (unsigned char)*text++;
}
return value % 5;
}
int main(void) {
const char *words[] = {"c", "cpp", "c"};
Item items[2] = {{"c", 0, NULL}, {"cpp", 0, NULL}};
Item *buckets[5] = {0};
for (int index = 0; index < 2; ++index) {
unsigned bucket = hash(items[index].key);
items[index].next = buckets[bucket];
buckets[bucket] = &items[index];
}
for (int index = 0; index < 3; ++index) {
Item *item = buckets[hash(words[index])];
for (; item; item = item->next) {
if (strcmp(item->key, words[index]) == 0) {
++item->count;
break;
}
}
}
printf("c=%d cpp=%d\n", items[0].count, items[1].count);
}
c=2 cpp=1
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> counts;
for (const std::string word : {"c", "cpp", "c"}) {
++counts[word];
}
std::cout << "c=" << counts["c"]
<< " cpp=" << counts["cpp"] << '\n';
}
c=2 cpp=1
C and C++ comparison
The compact C example uses fixed known keys to focus on buckets and chaining. std::unordered_map owns nodes, grows automatically, and supports arbitrary string keys.
Structures and operations are usually separate and allocation is explicit.
Classes and containers can preserve invariants and manage resources automatically.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add empty and capacity-boundary tests.
- Implement cleanup and verify no leaks remain.
- Compare operation complexity with a standard container.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- First Unique Character Find the first character that appears only once. Easy
- Character Frequency Count how often each character appears. Easy