DSA/Lesson 5 of 11/5 min read
Hashing
Hash tables, hash functions, collision resolution with chaining and open addressing, load factor, rehashing and hashing patterns.
On this page
Hash Table
A hash table maps keys to values with average O(1) insert, lookup and delete. It stores entries in an array of buckets and uses a hash function to pick the bucket.
bucket_index = hash(key) % capacity| Operation | Average | Worst |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
The worst case happens when many keys land in the same bucket. Language examples: Python dict, Java HashMap, C++ unordered_map, JavaScript Map.
Hash Function
Converts a key into an integer. A good hash function:
- is deterministic (same key, same hash);
- spreads keys uniformly across buckets;
- is fast to compute;
- uses the whole key (so similar keys do not cluster).
Common techniques
- Division method:
h(k) = k mod m, withma prime not close to a power of 2. - Multiplication method:
h(k) = floor(m * frac(k * A)), withAabout 0.618. - Polynomial rolling hash for strings:
h(s) = (s0 * p^(n-1) + s1 * p^(n-2) + ... ) mod M. Used in Rabin-Karp.
Contract in Java: if a.equals(b) then a.hashCode() == b.hashCode(). Overriding equals without hashCode breaks HashMap.
Pitfall: using mutable objects as keys. If the key changes after insertion, its hash changes and the entry is lost.
Collision
Two different keys hashing to the same bucket. By the pigeonhole principle collisions are unavoidable, and by the birthday paradox they show up sooner than expected (about sqrt(m) keys for m buckets). Two main strategies follow.
Separate Chaining
Each bucket holds a linked list (or a small tree) of entries.
bucket 0: (apple, 3) -> (grape, 1)
bucket 1: empty
bucket 2: (kiwi, 7)- Simple; deletion is easy.
- Performance degrades gracefully as the table fills.
- Extra memory for pointers, poorer cache locality.
Java 8 HashMap converts a chain to a red-black tree once it has more than 8 entries, making the worst case O(log n) per bucket.
Open Addressing
All entries live in the array itself. On collision, probe other slots until an empty one is found.
Linear Probing
Try h, h+1, h+2, .... Great cache performance, but suffers from primary clustering: long runs of filled slots grow longer.
Quadratic Probing
Try h + 1^2, h + 2^2, h + 3^2, .... Reduces primary clustering but causes secondary clustering (keys with the same start follow the same path).
Double Hashing
Step size comes from a second hash: h1(k) + i * h2(k). Best distribution of the three; h2 must never be 0.
Deletion with open addressing
You cannot just empty a slot, because it would break probe chains for later keys. Mark it with a tombstone instead. Tombstones are cleaned up on rehash.
| Chaining | Open addressing | |
|---|---|---|
| Memory | Extra pointers | Compact array |
| Cache | Poor | Good |
| Load factor above 1 | Possible | Impossible |
| Deletion | Easy | Needs tombstones |
| Used by | Java HashMap | Python dict, Go maps (variant) |
Load Factor
load factor = number of entries / number of buckets.
- Higher load factor: less memory, more collisions.
- Java
HashMapresizes at 0.75. Open addressing tables usually keep it below 0.5 to 0.7.
Expected probes for a successful search with linear probing grow like 1 / (1 - alpha), so performance collapses as the table nears full.
Rehashing
When the load factor crosses the threshold, allocate a bigger array (usually 2x) and reinsert every entry with the new capacity. A single rehash is O(n), but it happens rarely, so insert stays O(1) amortized, the same argument as dynamic arrays.
Pitfall in latency-sensitive systems: a rehash causes a pause. Incremental rehashing (Redis) moves a few buckets per operation.
Hash Set
A hash table that stores only keys. Used for membership checks and deduplication in O(1) average.
Hashing patterns in interviews
| Problem | Idea |
|---|---|
| Two Sum | Map value to index; look up target - x |
| Group anagrams | Key = sorted string or count tuple |
| Longest consecutive sequence | Set; start counting only at numbers with no x - 1 |
| Subarray sum equals k | Map prefix sum to count |
| First non-repeating character | Count map, then second pass |
| Contains duplicate within k | Sliding window set |
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return seen[target - x], i
seen[x] = iHash table vs balanced BST
| Hash table | Balanced BST (TreeMap) | |
|---|---|---|
| Lookup | O(1) average | O(log n) |
| Ordered iteration | No | Yes |
| Range queries, floor, ceiling | No | Yes |
| Worst case | O(n) | O(log n) |
Quick revision
- Hash table: average
O(1), worstO(n)when everything collides. - Good hash: deterministic, uniform, fast; never use mutable keys.
- Chaining stores lists per bucket; open addressing probes within the array.
- Linear probing clusters, quadratic reduces it, double hashing is best.
- Open addressing deletes with tombstones.
- Resize at a load factor threshold (0.75 in Java); rehash is
O(n)butO(1)amortized. - Use a BST instead when you need ordering or range queries.