Hash Tables

Dive into this core data structure concept.

A **Hash Table** (or Hash Map) is a data structure that stores data as key-value pairs. It uses a **hash function** to compute an index into an array of buckets or slots, from which the desired value can be found. This allows for very fast lookups, insertions, and deletions on average. C does not have a built-in hash table, so you have to implement it yourself. This involves creating an array of pointers (the buckets) and a hash function.

#define TABLE_SIZE 100

// Structure for a key-value pair entry
typedef struct Entry {
    char* key;
    int value;
    struct Entry* next;
} Entry;

// The hash table
Entry* hashTable[TABLE_SIZE];

// A simple hash function
unsigned int hash(char* key) {
    unsigned int hashValue = 0;
    while (*key) {
        hashValue = (hashValue << 5) + *key++;
    }
    return hashValue % TABLE_SIZE;
}

The key challenge in designing a hash table is dealing with **collisions**, which happen when two different keys hash to the same index. The code above implies a "chaining" strategy to handle collisions. Each bucket in the array is a pointer to the head of a linked list. When a collision occurs, the new key-value pair is added to this list.