A hash table is a data structure that maps keys to values using a hash function. The hash function converts the key into an index in an array, where the value is stored. This provides fast access to data, as the average time complexity for search, insertion, and deletion operations is O(1).
Hash tables are useful for scenarios where quick lookups, insertions, and deletions are required. They handle collisions (when two keys hash to the same index) using techniques such as chaining or open addressing.
Imagine a filing cabinet where each drawer represents a bucket in a hash table. The drawer's label is determined by a hashing function, and each drawer can contain multiple files (values) if there is a collision.
Consider a hash table with 5 buckets and the following keys: 10, 20, 30, 40, and 50. If we use a hash function that maps the key to an index by taking the modulus with the number of buckets (key % 5), the resulting table might look like this:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> hashTable;
hashTable[1] = "Value1";
hashTable[2] = "Value2";
std::cout << hashTable[1] << std::endl;
return 0;
}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> hashTable = new HashMap<>();
hashTable.put(1, "Value1");
hashTable.put(2, "Value2");
System.out.println(hashTable.get(1));
}
}
hash_table = {}
hash_table[1] = "Value1"
hash_table[2] = "Value2"
print(hash_table[1])
#include <stdio.h>
#define TABLE_SIZE 10
typedef struct {
int key;
char value[50];
} HashNode;
HashNode hashTable[TABLE_SIZE];
void insert(int key, char *value) {
int index = key % TABLE_SIZE;
hashTable[index].key = key;
strcpy(hashTable[index].value, value);
}
int main() {
insert(1, "Value1");
printf("%s\n", hashTable[1 % TABLE_SIZE].value);
return 0;
}