Hash Tables
Hash tables map keys to values using a hash function for fast lookups.
How They Work
- A hash function converts a key into an array index
- The value is stored at that index
- Collisions are handled via chaining or open addressing
Simple Implementation
class HashTable<V> {
private buckets: Array<Array<[string, V]>>;
private size: number;
constructor(size = 53) {
this.size = size;
this.buckets = Array.from({ length: size }, () => []);
}
private hash(key: string): number {
let total = 0;
for (let i = 0; i < key.length; i++) {
total = (total * 31 + key.charCodeAt(i)) % this.size;
}
return total;
}
set(key: string, value: V): void {
const index = this.hash(key);
const bucket = this.buckets[index];
const existing = bucket.find(([k]) => k === key);
if (existing) existing[1] = value;
else bucket.push([key, value]);
}
get(key: string): V | undefined {
const index = this.hash(key);
const pair = this.buckets[index].find(([k]) => k === key);
return pair?.[1];
}
}
Complexity
| Operation | Average | Worst |
|---|---|---|
| Insert | O(1) | O(n) |
| Lookup | O(1) | O(n) |
| Delete | O(1) | O(n) |
Worst case occurs when all keys hash to the same bucket.