Hash Tables Explained: Implementation in C and Python

In computer science, data organization dictates system efficiency. When you need to store, retrieve, and search through key-value pairs with lightning-fast performance, Hash Tables are the industry-standard data structure. Providing an average O(1) constant time complexity for insertions, lookups, and deletions, hash tables power everything from database indexing and caching layers to compiler symbol tables and dictionaries in modern programming languages.

This comprehensive guide explores the internal mechanics of hash tables, hash functions, collision resolution techniques, and provides clean, production-grade implementations in both C and Python.

1. How Hash Tables Work: Hash Functions and Arrays

At its core, a hash table is built on top of a standard fixed-size array. The magic happens through a hash function, which takes a key of arbitrary length and computes a fixed-size integer hash code. This hash code is then mapped to a valid array index using the modulo operator.

  • Key-Value Mapping: Keys are passed into the hash function to determine storage locations.
  • Deterministic Execution: Running the exact same key through the hash function must always yield the exact same index.
  • Uniform Distribution: A good hash function distributes keys uniformly across the array to minimize overlapping indices.

2. Collision Resolution Strategies

Because hash table arrays are finite while the possible set of keys is virtually infinite, two different keys will occasionally hash to the exact same array index—a scenario known as a collision. Two primary techniques resolve collisions:

  • Separate Chaining: Each array index points to a linked list of entries. When a collision occurs, the new key-value pair is simply appended to the list at that index.
  • Open Addressing (Linear Probing): When a collision occurs, the algorithm systematically probes adjacent array indices (e.g., index + 1) until the next open slot is found.

3. Hash Table Implementation in C (Separate Chaining)

Implementing a hash table in C requires manually managing memory, defining nodes for collision chaining, and writing a basic string hashing function.

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABLE_SIZE 10

// Node structure for chaining collisions
typedef struct HashNode {
    char* key;
    int value;
    struct HashNode* next;
} HashNode;

// Hash Table structure
typedef struct {
    HashNode* buckets[TABLE_SIZE];
} HashTable;

// Simple djb2 hash function
unsigned int hash(const char* key) {
    unsigned int hashValue = 5381;
    int c;
    while ((c = *key++)) {
        hashValue = ((hashValue << 5) + hashValue) + c;
    }
    return hashValue % TABLE_SIZE;
}

// Initialize Hash Table
HashTable* createTable() {
    HashTable* table = (HashTable*)malloc(sizeof(HashTable));
    for (int i = 0; i < TABLE_SIZE; i++) {
        table->buckets[i] = NULL;
    }
    return table;
}

// Insert key-value pair
void insert(HashTable* table, const char* key, int value) {
    unsigned int idx = hash(key);
    HashNode* newNode = (HashNode*)malloc(sizeof(HashNode));
    newNode->key = strdup(key);
    newNode->value = value;
    newNode->next = table->buckets[idx];
    table->buckets[idx] = newNode;
}

// Search value by key
int search(HashTable* table, const char* key) {
    unsigned int idx = hash(key);
    HashNode* current = table->buckets[idx];
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            return current->value;
        }
        current = current->next;
    }
    return -1; // Not found
}

int main() {
    HashTable* ht = createTable();
    insert(ht, "apple", 100);
    insert(ht, "banana", 200);
    
    printf("Apple value: %d\n", search(ht, "apple")); // Output: 100
    return 0;
}

4. Hash Table Implementation in Python

Python provides built-in hash tables via dictionaries (dict), which are highly optimized in C under the hood. However, building a custom hash table class using lists illustrates the underlying principles.

C
class CustomHashTable:
    def __init__(self, capacity: int = 10):
        self.capacity = capacity
        self.buckets = [[] for _ in range(capacity)]

    def _hash(self, key: str) -> int:
        return hash(key) % self.capacity

    def insert(self, key: str, value: int):
        idx = self._hash(key)
        for pair in self.buckets[idx]:
            if pair[0] == key:
                pair[1] = value
                return
        self.buckets[idx].append([key, value])

    def get(self, key: str) -> int:
        idx = self._hash(key)
        for pair in self.buckets[idx]:
            if pair[0] == key:
                return pair[1]
        raise KeyError(f"Key '{key}' not found in hash table.")

# Usage
ht = CustomHashTable()
ht.insert("devops", 404)
ht.insert("python", 500)
print(ht.get("devops")) # Output: 404

Conclusion

Hash tables are foundational to high-performance computing, providing average O(1) time complexity for data lookups. Understanding how hash functions map keys, how collision resolution handles overlapping indices, and how to implement them in lower-level languages like C and dynamic languages like Python equips developers to write exceptionally optimized code.