Hash Tables (DSA #6)
You have a billion URLs and want to know, for each one, whether it has been seen before. Scanning a list every time is \(O(n)\) per lookup, which is unusable. A hash table turns that lookup into an average \(O(1)\) operation by computing where a key should live instead of searching for it. It is the single most useful data structure in interview problems, because so many \(O(n^2)\) solutions collapse to \(O(n)\) the moment you can answer “have I seen this?” in constant time.
This chapter covers how hashing works, how collisions are handled, why the load factor matters, and the patterns — frequency maps, grouping, deduplication, and caches — that show up constantly. Cross-reference: Two Sum is the canonical hash-map problem.
The idea: compute the bucket
A hash table stores key–value pairs in an array of buckets. A hash function turns a key into an integer, and the bucket index is that integer modulo the array length:
\[ \text{index} = \text{hash}(key) \bmod \text{capacity} \]
To find a key, recompute the index and look in that bucket — no scanning. To insert, do the same. Average time is \(O(1)\) for lookup, insert, and delete.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=2.0cm, minimum height=0.62cm, font=\small, anchor=west}]
\foreach \i/\lab/\txt in {0/0/{("cat", 3)}, 1/1/{("dog", 5)}, 2/2/{}, 3/3/{("fox", 9)}} {
\node[b, fill=blue!10] at (0,-\i*0.72) {index \lab};
\node[anchor=west, font=\small] at (2.1,-\i*0.72) {\txt};
}
\node[font=\rmfamily\small, text=black!60, anchor=west] at (2.1,-2.5) {hash("dog") mod 4 = 1, so it lands in bucket 1};
\end{tikzpicture}
A set is a hash table with values but no keys (just membership); a map/dictionary stores key→value. Python’s dict and set are both hash tables, and almost every interview solution uses one.
Collisions: two keys, one bucket
Different keys can hash to the same index (there are far more possible keys than buckets). This is a collision, and how you resolve it defines the table.
Separate chaining. Each bucket holds a list (chain) of entries. Lookups walk that short chain. Simple, handles high load gracefully, and is what most textbooks and Python’s early implementations use.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=1.4cm, minimum height=0.6cm, font=\small},
n/.style={draw, thick, rounded corners=2pt, minimum height=0.55cm, font=\small\ttfamily, inner sep=5pt},
a/.style={->, thick}]
\foreach \i in {0,1,2,3} {
\node[b, fill=blue!10] (b\i) at (0,-\i*0.8) {bucket \i};
}
\node[n, fill=orange!22] (k1) at (2.6,-0.8) {dog};
\node[n, fill=orange!22] (k2) at (4.0,-0.8) {cow};
\draw[a] (b1.east) -- (k1.west);
\draw[a] (k1.east) -- (k2.west);
\draw[a] (b3.east) -- (4.0,-2.4) node[n, fill=green!20] {fox};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.4,-3.0) {collisions share a bucket as a short list};
\end{tikzpicture}
Open addressing. All entries live in the table itself; on collision, probe forward (linear probing) or by another rule until a free slot is found. No pointers, better cache locality, but deletions need tombstones and performance degrades as the table fills.
Load factor and resizing
The load factor is entries divided by buckets:
\[ \lambda = \frac{n}{\text{capacity}} \]
As \(\lambda\) approaches 1, chains lengthen and probes multiply — \(O(1)\) degrades toward \(O(n)\). Hash tables keep \(\lambda\) under a threshold (commonly ~0.66–0.75) by resizing: allocate a bigger table (usually double) and rehash every entry.
class HashMap:
def __init__(self, cap=8):
self.cap = cap
self.buckets = [[] for _ in range(cap)]
self.size = 0
def _index(self, key):
return hash(key) % self.cap
def put(self, key, val):
chain = self.buckets[self._index(key)]
for i, (k, _) in enumerate(chain):
if k == key:
chain[i] = (key, val); return
chain.append((key, val)); self.size += 1
if self.size > 0.75 * self.cap:
self._resize()
def _resize(self):
old = [kv for chain in self.buckets for kv in chain]
self.cap *= 2
self.buckets = [[] for _ in range(self.cap)]
self.size = 0
for k, v in old:
self.put(k, v)
Rehashing is \(O(n)\) but happens rarely, so insertion stays amortized \(O(1)\) — the same doubling argument as dynamic arrays (Chapter 2).
Pattern 1: frequency maps
Counting occurrences is the most common hash-table use. One pass builds the map; a second reads it.
def char_counts(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return counts
From here, problems like “first non-repeating character”, “majority element”, and “are two strings anagrams” become direct.
def are_anagrams(a, b):
return char_counts(a) == char_counts(b) # O(n) instead of O(n log n) sort
Pattern 2: have I seen this? (two-sum)
The lookup that turns \(O(n^2)\) into \(O(n)\). For each number, compute the complement needed to reach the target and ask whether it was already seen.
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen: # O(1) average
return [seen[need], i]
seen[x] = i
return []
The accompanying note Two Sum draws the running map frame by frame. The general lesson: whenever a nested-loop solution asks “does this exist?”, a hash set/map probably removes the inner loop.
Pattern 3: grouping
Hash tables group items that share a derived key. Grouping anagrams uses the sorted string (or a character-count tuple) as the key:
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
key = tuple(sorted(w)) # canonical form
groups[key].append(w)
return list(groups.values())
Deduplication is the same idea with a set:
def dedupe(items):
seen, out = set(), []
for x in items:
if x not in seen:
seen.add(x); out.append(x)
return out
Pattern 4: caches (dict + doubly linked list)
A hash map gives \(O(1)\) lookup but no ordering, so it cannot alone decide what to evict. Combine it with a doubly linked list that tracks recency: the map points to list nodes, the list orders them, and eviction removes the tail.
# sketch of an LRU cache: map for O(1) find, list for O(1) reorder
class LRU:
def __init__(self, cap):
self.cap = cap
self.map = {} # key -> node
self.head = self.tail = None # most recent ... least recent
def get(self, key):
if key not in self.map:
return None
node = self.map[key]
self._move_to_front(node) # O(1)
return node.val
This pairing — hash table for lookup, another structure for order — is the template for LRU/LFU caches, which are themselves a favorite interview design question.
Pitfalls
- Assuming worst-case \(O(1)\). Average is \(O(1)\); with many collisions or a bad hash it degrades to \(O(n)\). Adversarial keys can force this.
- Using unhashable keys. Lists and dicts cannot be keys; convert to a tuple or a string first.
- Mutating a key after insertion. If a key’s hash changes, the entry becomes unfindable. Keep keys immutable.
- Ignoring the load factor. A custom table that never resizes turns into a long linked list.
- Ordering assumptions. Standard hash maps do not preserve insertion order guarantees across languages; do not rely on iteration order (Python’s
dictdoes preserve it, but do not depend on it across implementations). - Space cost. A hash map is \(O(n)\) extra memory; sometimes sorting in place is the better trade.
What does the load factor measure, and why does resizing keep insertions amortized \(O(1)\)? Why do two-sum and LRU both need a hash table?
ASolution
The load factor is entries divided by buckets; as it grows, collisions and probes increase, so the table resizes before performance degrades. Doubling and rehashing occasionally costs \(O(n)\) but is spread over many \(O(1)\) insertions. Two-sum needs constant-time “have I seen the complement?”, and LRU needs constant-time key lookup; both would be linear-scan otherwise.
Next: Sorting Algorithms (DSA #7) — arranging data so that everything after it gets faster.