Hash Table
A foundational data structure that maps keys through a hash function to array buckets, enabling average O(1) lookup, insertion, and deletion
Table of Contents
Structure Diagram
What is Hash Table?
A foundational data structure that maps keys through a hash function to array buckets, enabling average O(1) lookup, insertion, and deletion. It is a core concept in Data Structures within CS.
Core Principles
A Hash Table (or Hash Map) passes any key through a hash function to compute an array index (hash(key) % capacity) and stores the associated value in that bucket. Because it jumps directly to the memory slot rather than scanning sequentially, lookups, insertions, and deletions run in average O(1) time.
Since infinitely many keys map onto finite buckets, hash collisions inevitably occur and are resolved via two main strategies:
- Separate Chaining: Each bucket stores a linked list or balanced tree of colliding entries (e.g., Java
HashMap). - Open Addressing: Colliding entries probe nearby empty slots inside the same backing array for better CPU cache locality (e.g., Python
dict, Rust'sHashMap/ SwissTable).
Practical Takeaways
- Watch load factor and rehashing spikes: Once occupancy crosses a threshold (typically
0.7–0.75), collisions degrade operations towardO(N). The table resizes and rehashes all keys—pre-allocating capacity when the expected size is known avoids sudden allocation stalls. - Use immutable keys only: Mutating a key after insertion changes its hash value, making the entry unreachable in the table. Stick to strings, numbers, or frozen tuples.
- Guard against HashDoS: Predictable hash functions let attackers craft thousands of colliding keys to force
O(N²)CPU exhaustion. Modern runtimes randomize hash seeds per process (e.g., SipHash) to neutralize this attack.
Notable Examples
- Language primitives: JavaScript
Map/Set, Pythondict, JavaHashMap, and Gomap. - In-memory caches: Redis and Memcached serving key-value lookups in microseconds.
- Database engines: Hash indexes for exact-match (
=) queries and Hash Joins for fast multi-table aggregation.
Practical Code Snippet
Copy and drop straight into your projectclass SimpleHashTable<V> { private buckets: Array<Array<[string, V]>> = Array.from({ length: 16 }, () => []); private hash(key: string): number { let h = 0; for (const ch of key) h = (h * 31 + ch.charCodeAt(0)) % this.buckets.length; return h; } set(key: string, value: V) { const bucket = this.buckets[this.hash(key)]; const entry = bucket.find(([k]) => k === key); if (entry) entry[1] = value; else bucket.push([key, value]); } get(key: string): V | undefined { return this.buckets[this.hash(key)].find(([k]) => k === key)?.[1]; }}