A hash table stores key-value pairs in an array and uses a hash function to turn each key directly into an array index. Instead of searching, you compute where the key must be. With a good hash function and a sensible load factor, insert, lookup and delete all run in O(1) on average, which makes hash maps and hash sets the most used tools in everyday programming and in interviews.
Think of it like
A wall of mailboxes
An apartment building has 100 mailboxes. Instead of searching every box for your mail, the carrier applies a rule to your name (say, a number computed from its letters, modulo 100) and drops the letter into that box. Two tenants can land on the same box (a collision), so each box may hold a few letters to sort through. Add more boxes as the building fills up and each box stays nearly empty.
How it works
- 1
Hash the key
Compute an integer
h(key)from the key. Equal keys must always produce equal hashes. - 2
Compress to an index
Map the hash into the table:
index = h(key) mod m, where m is the number of buckets. - 3
Visit the bucket
Go straight to that slot. No scanning of the rest of the table.
- 4
Resolve collisions
Other keys may share the slot, so compare keys for equality within the bucket (chaining) or along a probe sequence (open addressing).
- Hash function
- Maps a key to an integer. Must be deterministic and consistent with equality; should spread keys uniformly and be fast.
- Bucket (slot)
- One position of the underlying array.
- Collision
- Two different keys mapping to the same bucket. Unavoidable once there are more possible keys than buckets (pigeonhole principle).
- Load factor (α)
- Entries divided by buckets. Tables resize when α crosses a threshold.
Hash functions
A good hash function behaves like a random assignment of keys to buckets while remaining completely deterministic. Three classic constructions cover integers and strings.
Division method
Multiplication method
Polynomial string hashing
Every character influences the result, and its position matters, so "ab" and "ba" hash differently. The same polynomial, updated as a window slides, is the rolling hash behind Rabin-Karp search in String Matching (KMP, Rabin-Karp, Z).
Collision handling
Collisions arrive sooner than intuition suggests. By the birthday paradox, 23 people give a better-than-even chance that two share a birthday, and with m buckets you expect the first collision after only about 1.25√m keys. A table with a million buckets sees a collision after roughly 1,250 insertions. So every hash table needs a collision strategy.
Separate chaining
- Each bucket holds a small list (or tree) of entries
- Colliding keys are appended to the bucket's list
- Degrades gracefully; α can exceed 1
- Deletion is a simple list removal
- Extra pointers and allocations; weaker cache locality
Open addressing
- All entries live in the array itself
- On collision, probe other slots in a fixed sequence
- Excellent cache behavior, no per-entry allocation
- Needs α < 1, and performance collapses as α nears 1
- Deletion needs tombstones or backward shifting
| Probing scheme | i-th probe | Strength | Weakness |
|---|---|---|---|
| Linear | (h(k) + i) mod m | Sequential memory access, very cache-friendly | Primary clustering: occupied runs grow and merge |
| Quadratic | (h(k) + c₁·i + c₂·i²) mod m | Breaks up long runs | Secondary clustering; may miss free slots unless m and the constants are chosen carefully (for example m prime and α < 1/2) |
| Double hashing | (h₁(k) + i·h₂(k)) mod m | Each key gets its own step size: closest to ideal uniform probing | Two hash computations; h₂(k) must be non-zero and coprime with m |
| Key | h(k) = k mod 13 | Slots probed | Final slot |
|---|---|---|---|
| 18 | 5 | 5 | 5 |
| 41 | 2 | 2 | 2 |
| 22 | 9 | 9 | 9 |
| 44 | 5 | 5, 6 | 6 |
| 59 | 7 | 7 | 7 |
| 32 | 6 | 6, 7, 8 | 8 |
| 31 | 5 | 5, 6, 7, 8, 9, 10 | 10 |
| 73 | 8 | 8, 9, 10, 11 | 11 |
Load factor, resizing and rehashing
The expected cost of an operation depends on the load factor, not on n. Chaining degrades linearly in α; open addressing degrades sharply as the table nears full. These are the classic expected probe counts under uniform hashing.
| Load factor α | Chaining, unsuccessful (≈ 1 + α) | Linear probing, successful | Linear probing, unsuccessful |
|---|---|---|---|
| 0.50 | 1.5 | 1.5 | 2.5 |
| 0.75 | 1.75 | 2.5 | 8.5 |
| 0.90 | 1.9 | 5.5 | 50.5 |
- 1
Detect
After an insert, check whether α exceeds the threshold (0.75 in Java's
HashMap, 2/3 in CPython'sdict). - 2
Allocate
Create a bucket array roughly twice as large (Java keeps capacities at powers of two).
- 3
Rehash
Re-insert every entry by recomputing its index for the new m. Entries cannot simply be copied, because
h(key) mod mchanges when m changes. - 4
Swap
Replace the old array. One resize costs O(n), but doubling makes insert O(1) amortized, exactly like a dynamic array (Arrays & Dynamic Arrays).
Deletion with tombstones
With chaining, deletion just removes the entry from its bucket's list. With open addressing it is subtle. In the trace above, key 31 was placed at slot 10 after probing 5 through 9. If we delete 44 by emptying slot 6, a later search for 31 starts at 5, reaches the empty slot 6 and stops, wrongly concluding that 31 is absent.
- Tombstones: mark a deleted slot as
DELETEDinstead of empty. Searches skip over it and keep probing; inserts may reuse it. - Cleanup: tombstones count toward the load for probing purposes, so tables periodically rehash to purge them.
- Backward-shift deletion: with linear probing you can instead move later entries of the cluster back into the hole, avoiding tombstones entirely.
Average case vs worst case
Average: O(1)
- Assumes the hash spreads keys roughly uniformly
- Load factor kept below a constant by resizing
- Expected bucket size is O(1 + α)
- Holds in practice for ordinary data and good hash functions
Worst: O(n)
- Every key lands in the same bucket
- Caused by a poor hash function or a malicious attacker
- Each lookup scans all n entries
- Inserting n such keys costs O(n²) in total
How real languages implement it
| Implementation | Strategy | Notable details |
|---|---|---|
Python dict and set | Open addressing | Perturbation-based probing that mixes in higher hash bits; resizes at about 2/3 full; dict preserves insertion order (since 3.7) with a compact index-plus-entries layout |
Java HashMap | Separate chaining | Power-of-two capacity, default load factor 0.75, spreads hashes with h ^ (h >>> 16); a bucket becomes a red-black tree once it holds 8 entries and the table has at least 64 buckets |
C++ std::unordered_map | Separate chaining | Node-based so references stay valid across rehashes; default max_load_factor is 1.0 |
JavaScript Map and Set | Engine-specific hash tables | Iterate in insertion order; plain objects are also hash-like but have prototype and key-conversion quirks |
Rust HashMap, Abseil flat_hash_map | Open addressing (SwissTable) | Groups of slots with one metadata byte each, scanned with SIMD instructions |
Hash flooding
If an attacker knows your hash function, they can craft thousands of keys that all collide, for example as HTTP form parameters parsed into a map. Each insertion then scans an ever-longer chain, the server burns O(n²) CPU on a single request, and service grinds to a halt. Public disclosures in 2011 showed that the web stacks of PHP, Java, Python, Ruby and others were all vulnerable.
- Keyed, randomized hashing: Python randomizes string hashes per process (since 3.3) and uses SipHash (since 3.4); Rust's default hasher is SipHash-1-3. Without the secret seed, attackers cannot predict collisions.
- Bounded worst case: Java's treeified buckets cap the damage at O(log n) per operation.
- Input limits: cap the number of parameters, headers or JSON keys accepted per request.
Common patterns
| Pattern | Map from → to | Example problems |
|---|---|---|
| Complement lookup | value → index | Two Sum: for each x, check whether target - x was seen |
| Frequency counting | item → count | Top K frequent, first unique character, valid anagram |
| Grouping | canonical key → list | Group anagrams (key = sorted word), group by pattern |
| Seen set | item → present | Contains duplicate, cycle detection, longest consecutive sequence |
| Prefix sums + counts | prefix sum → occurrences | Subarray sum equals k (Prefix Sums & Difference Arrays) |
| Memoization | subproblem → answer | Top-down DP (DP Fundamentals) |
| Index for O(1) updates | key → node | LRU cache: map plus doubly linked list (LRU & LFU Cache) |
def two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen: # O(1) average lookup
return [seen[target - x], i]
seen[x] = i
return []
# The brute force checks every pair: O(n^2). The map makes it a single O(n) pass.Complexity
| Operation | Average | Worst | Notes |
|---|---|---|---|
| Insert | O(1) | O(n) | Amortized: includes occasional O(n) resize |
| Lookup | O(1) | O(n) | Worst case when all keys collide |
| Delete | O(1) | O(n) | Open addressing uses tombstones |
| Resize / rehash | O(n) | O(n) | Happens rarely; amortized into inserts |
| Iterate all entries | O(n + m) | O(n + m) | Visits every bucket |
| Lookup, Java treeified bucket | O(1) | O(log n) | For Comparable keys |
Space is O(n + m). Averages assume a well-distributed hash function and a load factor bounded by a constant.
Implementation
String keys hashed with a polynomial (Horner's rule), buckets of key-value pairs, and a full rehash into twice as many buckets when the load factor exceeds 0.75.
from typing import Generic, Optional, TypeVar
V = TypeVar("V")
class ChainedHashMap(Generic[V]):
MAX_LOAD = 0.75
def __init__(self, capacity: int = 8) -> None:
self._buckets: list[list[tuple[str, V]]] = [[] for _ in range(capacity)]
self._size = 0
@staticmethod
def _hash(key: str) -> int:
h = 0
for ch in key: # Horner's rule, base 31
h = (h * 31 + ord(ch)) & 0xFFFFFFFF # keep it in 32 bits
return h
def _bucket(self, key: str) -> list[tuple[str, V]]:
return self._buckets[self._hash(key) % len(self._buckets)]
def put(self, key: str, value: V) -> None: # O(1) average
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value) # update in place
return
bucket.append((key, value))
self._size += 1
if self._size / len(self._buckets) > self.MAX_LOAD:
self._resize(2 * len(self._buckets))
def get(self, key: str) -> Optional[V]: # O(1) average
for k, v in self._bucket(key):
if k == key:
return v
return None
def remove(self, key: str) -> bool: # O(1) average
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket.pop(i)
self._size -= 1
return True
return False
def _resize(self, new_capacity: int) -> None: # O(n): every key gets a new index
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[self._hash(k) % new_capacity].append((k, v))
def __len__(self) -> int:
return self._size
m: ChainedHashMap[int] = ChainedHashMap()
for i, word in enumerate(["apple", "banana", "cherry", "date", "elder", "fig", "grape"]):
m.put(word, i) # the 7th insert triggers a resize
m.put("apple", 100)
m.remove("banana")
print(len(m), m.get("apple"), m.get("banana"), m.get("grape")) # 6 100 None 6Key takeaways
- A hash table computes an index from the key,
h(key) mod m, so insert, lookup and delete are O(1) on average. - Collisions are inevitable; resolve them with separate chaining or open addressing (linear, quadratic or double hashing).
- Performance depends on the load factor α = n/m; resize by doubling and rehash every key to keep inserts amortized O(1).
- Open addressing needs tombstones (or backward shifting) for deletion, or probe chains break.
- The worst case is O(n) when keys collide; Java treeifies hot buckets and Python and Rust use keyed hashes against flooding.
- Two Sum, frequency counting, grouping, seen sets and memoization are all hash map patterns.
Common pitfalls
- Overriding
equalswithouthashCode(or__eq__without__hash__), so equal keys land in different buckets. - Mutating an object after using it as a key, which makes the entry unreachable.
- Emptying slots on delete in an open-addressing table instead of leaving tombstones.
- Treating O(1) as guaranteed: ignoring resize spikes, poor hash functions or adversarial input.
- Relying on iteration order of a plain hash map (
HashMap,unordered_map), which is unspecified and can change after a resize.
Interview tips
- State the mapping explicitly ("value to index") and the space cost (O(n)) whenever you use a map.
- If asked to design a hash map, cover the hash function, collision strategy, load factor, resizing and deletion.
- Mention average vs worst case and how real implementations defend the worst case (treeification, randomized hashing).
Real-world applications
- Dictionaries, sets, symbol tables in compilers and interpreters, and object property storage.
- Caches (memcached, Redis, CDN edge caches) and memoization.
- Database hash indexes and hash joins; deduplication in data pipelines.
- Routing and load distribution through hashing (see Consistent Hashing).
Practice problems
Test yourself
A hash table holds 600 entries in 800 buckets. What is its load factor?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.