Hash Tables
Average O(1) insert, lookup and delete — hash functions, collisions, load factor, resizing and how HashMap really works.
A hash table maps keys to values with average O(1) insert, lookup and delete. It is arguably the most useful data structure in practice: Java's HashMap/HashSet, Python's dict/set, JavaScript's Map/Set, database hash indexes, caches and compilers' symbol tables.
The idea
Keep an array of buckets. To store a key, run it through a hash function that turns it into an integer, then map that integer to a bucket index:
Lookup repeats the same computation and goes straight to the bucket — no searching.
What makes a good hash function
- Deterministic — equal keys always produce equal hashes.
- Uniform — spreads keys evenly over buckets.
- Fast — it runs on every operation.
- For hash tables it does not need to be cryptographic (see Hash functions for that kind).
Collisions
Different keys can land in the same bucket — guaranteed once there are more keys than buckets (pigeonhole principle). There are two main strategies.
Separate chaining
Each bucket holds a small list of entries. Lookup hashes to the bucket, then scans its list.
Java's HashMap uses chaining, and since Java 8 converts a bucket's list into a red-black tree once it exceeds 8 entries, so a pathological bucket costs O(log n) instead of O(n).
Open addressing
All entries live in the array itself. On collision, probe other slots:
- Linear probing: try
i, i+1, i+2, …— very cache-friendly, but suffers primary clustering. - Quadratic probing:
i + 1², i + 2², …. - Double hashing: step size from a second hash function.
Deletion needs tombstones (a "deleted" marker) so later probes don't stop early. Python's dict and many high-performance tables (Google's SwissTable, Rust's HashMap) use open addressing.
Load factor and resizing
As α grows, chains (or probe sequences) get longer and operations slow down. When α crosses a threshold — 0.75 in Java, about 2/3 in Python — the table doubles its capacity and rehashes every entry. Like dynamic arrays, this is O(n) occasionally but amortized O(1) per insert.
| Operation | Average | Worst case |
|---|---|---|
| Insert | O(1) | O(n) (all keys collide) |
| Lookup | O(1) | O(n) — O(log n) for treeified Java buckets |
| Delete | O(1) | O(n) |
| Iterate in sorted order | — | Not supported; use a balanced BST / TreeMap |
A minimal hash map
class MyHashMap<K, V> {
private static class Entry<K, V> {
final K key; V val; Entry<K, V> next;
Entry(K k, V v, Entry<K, V> n) { key = k; val = v; next = n; }
}
@SuppressWarnings("unchecked")
private Entry<K, V>[] buckets = new Entry[16];
private int size;
private int idx(Object key, int cap) {
int h = key.hashCode();
h ^= (h >>> 16); // spread high bits (like java.util.HashMap)
return h & (cap - 1); // cap is a power of two → fast modulo
}
public V get(K key) {
for (Entry<K, V> e = buckets[idx(key, buckets.length)]; e != null; e = e.next)
if (e.key.equals(key)) return e.val;
return null;
}
public void put(K key, V val) {
int i = idx(key, buckets.length);
for (Entry<K, V> e = buckets[i]; e != null; e = e.next)
if (e.key.equals(key)) { e.val = val; return; }
buckets[i] = new Entry<>(key, val, buckets[i]);
if (++size > buckets.length * 3 / 4) resize();
}
@SuppressWarnings("unchecked")
private void resize() {
Entry<K, V>[] old = buckets;
buckets = new Entry[old.length * 2];
for (Entry<K, V> head : old)
for (Entry<K, V> e = head; e != null; e = e.next) {
int i = idx(e.key, buckets.length);
buckets[i] = new Entry<>(e.key, e.val, buckets[i]);
}
}
}class MyHashMap:
def __init__(self, capacity=8):
self.buckets = [[] for _ in range(capacity)]
self.size = 0
def _bucket(self, key):
return self.buckets[hash(key) % len(self.buckets)]
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
def put(self, key, value):
b = self._bucket(key)
for i, (k, _) in enumerate(b):
if k == key:
b[i] = (key, value)
return
b.append((key, value))
self.size += 1
if self.size > len(self.buckets) * 0.75:
self._resize()
def _resize(self):
old = self.buckets
self.buckets = [[] for _ in range(len(old) * 2)]
self.size = 0
for b in old:
for k, v in b:
self.put(k, v)class MyHashMap<V> {
private buckets: [string, V][][] = Array.from({ length: 8 }, () => []);
private size = 0;
private hash(key: string): number {
let h = 0;
for (let i = 0; i < key.length; i++) h = (Math.imul(h, 31) + key.charCodeAt(i)) | 0;
return h >>> 0;
}
private bucket(key: string) {
return this.buckets[this.hash(key) % this.buckets.length];
}
get(key: string): V | undefined {
return this.bucket(key).find(([k]) => k === key)?.[1];
}
put(key: string, val: V) {
const b = this.bucket(key);
const e = b.find(([k]) => k === key);
if (e) { e[1] = val; return; }
b.push([key, val]);
if (++this.size > this.buckets.length * 0.75) this.resize();
}
private resize() {
const old = this.buckets.flat();
this.buckets = Array.from({ length: this.buckets.length * 2 }, () => []);
this.size = 0;
for (const [k, v] of old) this.put(k, v);
}
}Using hash maps in interviews
Hash maps turn O(n²) "search for a partner" loops into O(n) single passes.
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value → index
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[]{j, i};
seen.put(nums[i], i);
}
return new int[0];
}def two_sum(nums: list[int], target: int) -> list[int]:
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>(); // value -> index
for (let i = 0; i < nums.length; i++) {
const j = seen.get(target - nums[i]);
if (j !== undefined) return [j, i];
seen.set(nums[i], i);
}
return [];
}Common uses: counting frequencies, deduplication (Set), grouping (anagrams), memoisation in dynamic programming, prefix-sum counts (Prefix sum), and graph adjacency lists.
- Hash → bucket index gives average O(1) operations.
- Collisions are resolved by chaining or open addressing.
- Keep the load factor bounded by resizing (amortized O(1)).
- Worst case is O(n); languages randomise hash seeds to defend against hash-flooding attacks.
- Equal objects must have equal hash codes.
QHow does Java's HashMap work internally?medium
An array of buckets (capacity a power of two, default 16). hash = h ^ (h >>> 16), index = hash & (n-1). Collisions chain in a linked list, converted to a red-black tree when a bucket exceeds 8 entries (and the table has at least 64 buckets). When size exceeds capacity × 0.75 the table doubles and entries are redistributed. It allows one null key and is not thread-safe — use ConcurrentHashMap.
QWhat is a hash-flooding attack?hard
An attacker submits many keys that collide (e.g., HTTP form parameter names), degrading every operation to O(n) and the server to O(n²) CPU. Defences: randomised per-process hash seeds (SipHash in Python, Rust, Ruby), treeified buckets (Java), and request limits.
QWhen would you choose a TreeMap over a HashMap?easy
When you need keys in sorted order, range queries (floorKey, subMap), or a guaranteed O(log n) worst case instead of average O(1).
QLongest consecutive sequence in an unsorted array in O(n).medium
Put all numbers in a set. For each x where x−1 is not in the set (the start of a run), count upward while x+1, x+2, … exist. Every number is visited at most twice.