Hashing and Hash Tables (DSA Core #4)
A hash table turns a key into an array index. That is the entire idea, and it is why lookup is usually constant time: one arithmetic step, one memory access. The “usually” is where the interview questions live.
Hash functions and collisions
A hash function maps an arbitrary key to a bucket:
\[ h(k) = f(k) \bmod m, \qquad 0 \le h(k) < m \]
Three properties matter:
- Deterministic — the same key must give the same bucket every time.
- Uniform — keys should spread evenly across buckets. Any clustering turns \(O(1)\) into \(O(n)\).
- Cheap — the hash must cost less than the search it replaces.
You cannot map a large key space into m buckets without collisions: there are
more possible keys than buckets. That is not a bug in your function, it is the
pigeonhole principle. Collisions are handled by the table, not avoided.
For strings, a polynomial hash is standard:
size_t stringHash(const string& s) {
size_t h = 1469598103934665603ULL; // FNV offset basis
for (unsigned char c : s) {
h ^= c;
h *= 1099511628211ULL; // FNV prime, wraps mod 2^64
}
return h;
}
std::hash<std::string> does something similar and is not guaranteed stable
across runs or compilers — never persist a std::hash value.
Modulus choice matters. m = 2^k is fast but uses only the low bits of the hash,
which is bad for keys that differ in the high bits. A prime modulus (or a
well-mixed function) spreads better. unordered_map in libstdc++ uses prime
bucket counts for this reason.
ASolution
It maps a larger key space into a smaller bucket range. Two different keys must eventually land in the same bucket; the table has to resolve that.
Collision resolution
Separate chaining. Each bucket holds a list (or a small vector) of entries. Lookup hashes to the bucket and scans the chain.
struct Entry { int key, val; };
vector<vector<Entry>> buckets; // size = m
Open addressing. All entries live in the table itself. On a collision, probe the next slot by some rule until an empty one is found.
| Probing | Next slot | Behaviour |
|---|---|---|
| Linear | (h + i) mod m |
fast, but clusters grow into long runs |
| Quadratic | (h + i²) mod m |
less primary clustering, may not reach every slot |
| Double hashing | (h + i·g(k)) mod m |
best spread, two hash computations |
// linear probing insert
size_t i = h & (m - 1); // m a power of two
while (used[i]) i = (i + 1) & (m - 1); // wraps, may loop if table is full
table[i] = entry;
used[i] = true;
Deletion is the trap in open addressing. You cannot just clear the slot, because a later probe may have skipped over it; clearing creates a hole that breaks search. Use a tombstone: a third state meaning “was occupied, now deleted, keep probing”. Tombstones accumulate and eventually force a rehash.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=0.85cm, minimum height=0.62cm, font=\scriptsize\bfseries}]
\foreach \i in {0,...,5} \node[b, fill=gray!6] (s\i) at (\i*0.95,0) {};
\node[b, fill=orange!25] at (0.95,0) {k1};
\node[b, fill=orange!25] at (4.75,0) {k5};
\node[b, fill=blue!15] at (0.95,-1.0) {k4};
\node[b, fill=blue!15] at (0.95,-1.62) {k9};
\node[font=\scriptsize, anchor=west] at (5.6,0) {bucket 1: chain};
\draw[->, thick] (1.35,-0.32) -- (1.35,-0.68);
\draw[->, thick] (1.35,-1.32) -- (1.35,-1.5);
\end{tikzpicture}
Chaining versus open addressing:
| Chaining | Open addressing | |
|---|---|---|
| Memory | extra pointers per entry | entries stored inline |
| Cache | pointer chase per chain node | contiguous, probe-friendly |
| Deletion | unlink | tombstone |
| Load factor | can exceed 1 | must stay below 1 |
| Worst case | one long chain | long probe run |
std::unordered_map uses chaining. It keeps the load factor at or below 1.0 by
default, so chains average about one element.
a deleted slot?
ASolution
A search stops at the first empty slot. Clearing a slot that a probe sequence passed through makes later keys unreachable, so deletion must leave a marker that means “keep probing”.
Average versus worst case
The average cost follows from the load factor \(\alpha = n/m\), the fraction of buckets occupied.
- Chaining, unsuccessful search: expected probes \(\approx \alpha\).
- Chaining, successful search: \(\approx 1 + \alpha/2\).
- Open addressing, linear probing: successful \(\approx \tfrac{1}{2}(1 + 1/(1-\alpha))\), unsuccessful \(\approx \tfrac{1}{2}(1 + 1/(1-\alpha)^2)\).
At \(\alpha = 0.75\), linear probing averages about 2.5 probes for a hit — still constant. At \(\alpha = 0.99\) it averages 50. That is why the table resizes before getting full, typically doubling when the load factor crosses 0.7–1.0. A resize rehashes every key: \(O(n)\) once, amortized \(O(1)\) per insert.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
a/.style={->, thick},
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\scriptsize}]
\foreach \i in {0,...,5} \node[c] (b\i) at (\i*0.8,0) {};
\foreach \i/\n in {1/1,3/2,4/3} \fill[orange!30] (\i*0.8,0) circle (0.22);
\node[font=\scriptsize, anchor=north] at (2.0,-0.4) {alpha = 3/6 = 0.5};
\node[font=\scriptsize, anchor=south] at (4.0,0.45) {long run: worse};
\end{tikzpicture}
The worst case is \(O(n)\) per operation: all \(n\) keys in one bucket, or a probe
sequence that walks the table. With a good hash and a bounded load factor this
needs deliberate adversary action. Which is real: if an attacker can choose keys
and knows the hash, they can collide everything and turn your \(O(n)\) program into
\(O(n^2)\). unordered_map mitigates this with randomized hashing for strings in
some implementations; competitive judges have used the attack against the default
one.
The honest statement for an interview: average \(O(1)\), worst \(O(n)\), expected \(O(1)\) under a uniform hash assumption. Nothing guarantees \(O(1)\) per operation the way a balanced tree guarantees \(O(\log n)\).
single chain. What is the cost of one lookup?
ASolution
\(O(n)\) — one million comparisons, because the chain is scanned linearly. The average-case bound does not apply once the distribution is that bad.
Sets and maps in C++
| Container | Order | Lookup | Notes |
|---|---|---|---|
unordered_set / unordered_map |
none | expected \(O(1)\) | hashing, chaining |
set / map |
sorted | \(O(\log n)\) | red-black tree |
multiset / multimap |
sorted | \(O(\log n)\) | duplicate keys allowed |
unordered_map<string, int> freq;
freq["nvidia"]++; // inserts 0 then increments
if (freq.count("amd")) { /* ... */ } // 0 or 1
freq.erase("amd");
for (const auto& [k, v] : freq) cout << k << ' ' << v << '\n';
operator[] inserts a default value when the key is missing. That is
convenient for counters and a bug when you only meant to read. Use find or
contains (C++20) for a read:
auto it = freq.find("amd");
if (it != freq.end()) cout << it->second;
For custom keys, provide a hash. pair<int,int> has no standard hash, and this is
a common OA need (grid coordinates, pairs of ids):
struct PairHash {
size_t operator()(const pair<int,int>& p) const {
return (size_t)p.first * 1000003u ^ ((size_t)p.second + 0x9e3779b9u);
}
};
unordered_map<pair<int,int>, int, PairHash> grid;
A weak x * 31 + y for grid coordinates collides a lot on anti-diagonals; mixing
with a large odd constant avoids the obvious patterns. set<pair<int,int>>
needs no hash and is \(O(\log n)\) — often fast enough and simpler.
freq[key] and freq.at(key)?ASolution
operator[] inserts a default-constructed value if the key is absent, so it can
grow the map. at throws out_of_range instead. Neither is a pure lookup;
find is.
Frequency maps
Counting is the most common hash-table use in an OA. Two patterns cover most of it:
Count, then query. Anagram checks, majority element, first unique character, top-k frequent.
vector<int> topKFrequent(const vector<int>& a, int k) {
unordered_map<int,int> cnt;
for (int x : a) ++cnt[x];
vector<pair<int,int>> v(cnt.begin(), cnt.end()); // {value, count}
sort(v.begin(), v.end(), [](auto& x, auto& y) {
return x.second > y.second; // descending count
});
vector<int> out;
for (int i = 0; i < k; ++i) out.push_back(v[i].first);
return out;
}
Sorting is \(O(n \log n)\); a min-heap of size k is \(O(n \log k)\), and bucket sort
by count is \(O(n)\) because a count is at most \(n\).
Running prefix with a hash map. Count subarrays with sum k:
long long subarraysWithSum(const vector<int>& a, int k) {
unordered_map<long long,int> seen{{0, 1}}; // empty prefix
long long sum = 0, count = 0;
for (int x : a) {
sum += x;
count += seen[sum - k]; // prefixes that leave sum k
++seen[sum];
}
return count;
}
The map stores how many times each prefix sum has occurred. For each i, the
number of valid j < i is the number of prefixes equal to sum - k. This is the
prefix-sum idea from Ch. 1 with memory instead of subtraction — and it handles
negative numbers, which a sliding window does not.
Variants: divisible by k (store sum % k, normalizing negatives), longest
subarray with sum k (store the first index per prefix), binary subarrays with
sum k (same thing).
{0: 1}?ASolution
It counts the empty prefix, so a subarray starting at index 0 is found when
sum == k. Without it, those subarrays are missed.
Hashing versus balanced search trees
unordered_map |
map |
|
|---|---|---|
| Lookup | expected \(O(1)\), worst \(O(n)\) | \(O(\log n)\) guaranteed |
| Ordered iteration | no | yes, sorted |
Range queries (lower_bound) |
impossible | \(O(\log n)\) |
| Memory | buckets + nodes | nodes |
| Iterator stability | invalidated on rehash | stable across inserts |
| Key requirement | hash + equality | strict weak ordering |
Choose the tree when you need order: lower_bound, smallest key \(\ge x\), range
summaries, or deterministic performance. Choose the hash map when you need raw
speed on point lookups and the keys are well distributed.
map in C++ is a red-black tree, so pointer/reference stability holds: inserting
does not move existing nodes. That matters for the LRU cache below, where the map
stores iterators into a list — those iterators survive unrelated inserts.
x”. Why is ahash map the wrong tool?
ASolution
Hash maps have no order, so there is no way to find a nearest key without
scanning all of them. A balanced BST gives lower_bound in \(O(\log n)\).
LRU cache: a map plus a doubly linked list
Requirements: get(key) and put(key, value) in \(O(1)\), and when capacity is
exceeded evict the least recently used key.
Each structure alone fails:
- Hash map alone: \(O(1)\) lookup but no recency order.
- Linked list alone: \(O(1)\) move-to-front but \(O(n)\) lookup.
Combine them: the map goes from key to the list node, and the list holds the recency order. Front = most recent, back = least recent.
class LRUCache {
int cap;
list<pair<int,int>> order; // {key, value}, front = newest
unordered_map<int, list<pair<int,int>>::iterator> pos;
public:
explicit LRUCache(int capacity) : cap(capacity) {}
int get(int key) {
auto it = pos.find(key);
if (it == pos.end()) return -1;
order.splice(order.begin(), order, it->second); // move node to front, O(1)
return it->second->second;
}
void put(int key, int value) {
auto it = pos.find(key);
if (it != pos.end()) {
it->second->second = value;
order.splice(order.begin(), order, it->second);
return;
}
if ((int)order.size() == cap) {
int old = order.back().first;
order.pop_back();
pos.erase(old); // keep map and list in sync
}
order.emplace_front(key, value);
pos[key] = order.begin();
}
};
splice moves a node between positions without allocating or invalidating
iterators — that is why std::list is the right container here, and why the map
can safely hold list::iterators.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=1.1cm, minimum height=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n, fill=green!25] (a) at (0,0) {A};
\node[n] (b) at (1.6,0) {B};
\node[n] (c) at (3.2,0) {C};
\node[n, fill=red!15] (d) at (4.8,0) {D};
\draw[a] (a) -- (b);
\draw[a] (b) -- (c);
\draw[a] (c) -- (d);
\node[font=\scriptsize, anchor=north] at (0,-0.45) {newest};
\node[font=\scriptsize, anchor=north] at (4.8,-0.45) {evict next};
\node[font=\scriptsize, anchor=west] at (6.0,0) {map: key -> node};
\end{tikzpicture}
Both operations do a constant number of map and list operations, so \(O(1)\) each. The cache is the standard answer to “design a structure with \(O(1)\) get/put and eviction”, and the same shape solves LFU with an extra frequency list.
Two details that break it: forgetting to update the map when evicting (the map
keeps a dangling iterator), and using a vector instead of a list (erase is
\(O(n)\) and iterators are invalidated).
ASolution
get has to move the existing node to the front in \(O(1)\). Without a handle to
the node, you would have to search the list, which is \(O(n)\).
Bugs and edge cases
operator[]inserts. Reading a missing key withm[k]grows the map and can change iteration order. Usefind.- Rehash invalidation. Inserting can rehash and invalidate all iterators. Never hold an iterator across an insert.
- Missing custom hash.
unordered_map<pair<...>>does not compile. Write the hash, and mix both fields. - Mutable keys. Changing a key after insertion corrupts the table; store
constkeys. - Floating-point keys.
0.1 + 0.2 != 0.3. Use integers (scaled) or a tolerance with a different structure. - Negative modulo.
sum % kis negative in C++ for negative sums. Normalize:((sum % k) + k) % k. - Load factor never bounded. A table that only grows in buckets but not in
rehash trigger degrades silently.
unordered_maphandles this; a hand-rolled one does not. - Deleting during iteration. Erasing invalidates the current iterator. Use
it = m.erase(it)and do not increment.
put on an existingkey. What did you forget?
ASolution
Either the value update in the node, or the splice that marks the key as most
recently used. Updating the value without moving the node makes it the next
eviction candidate.
Next: Trees and Binary Search Trees (DSA Core #5) — traversals, BST operations, and dynamic programming on trees.