Chapter 07
Hashing & Hash Tables
2 topics · 1 sections · beginner-friendly study notes · Updated
A hash table maps keys to array indices using a hash function, giving average O(1) insert, search and delete.
Collisions are resolved by chaining or open addressing; hash maps/sets turn many O(n^2) scans into O(n).
Hash maps are the most used data structure in interviews; GATE asks probing outcomes and expected probe counts.
Caches, symbol tables, database indexes, deduplication, counting, password storage (with cryptographic hashes).
Hash Functions & Collisions
A hash function h(k) maps a key to an index in [0, m-1]; two different keys with the same index collide. Collisions are inevitable (pigeonhole principle) when the key universe is larger than m and are handled by separate chaining or open addressing.
In short: Turn a key into a bucket number; if two keys land in one bucket, resolve it with a strategy.

Think about it
GATE questions: insert a sequence into a table with probing, count collisions, expected probes, load factor.
Good hash: deterministic, uniform, fast.
Division method h(k) = k mod m (choose m prime, not a power of 2 which only uses low bits).
Multiplication method: floor(m * frac(k*A)) with A about 0.618.
String hash: polynomial s[0]*p^(n-1)+...
+s[n-1] mod m (rolling hash for Rabin-Karp).
Load factor alpha = n/m.
Chaining: each slot holds a list; expected search time Theta(1 + alpha) under simple uniform hashing; alpha may exceed 1; worst case O(n) if all keys hash together (Java HashMap converts long buckets to trees: O(log n)).
Open addressing: all keys in the table (alpha <= 1): linear probing h(k,i)=(h(k)+i) mod m suffers primary clustering; quadratic probing (h + c1*i + c2*i^2) suffers secondary clustering and may not visit all slots unless m is prime and alpha < 0.5 (or m is a power of two with triangular numbers); double hashing h1 + i*h2 with h2 coprime to m minimizes clustering.
Expected probes for unsuccessful search with open addressing about 1/(1-alpha); successful about (1/alpha) ln(1/(1-alpha)).
Deletion in open addressing needs tombstones (mark deleted) else probing chains break.
Resize when alpha exceeds threshold (e.
g.
0.75): allocate 2m, rehash all keys O(n), amortized O(1) insert.
Python dict/set: average O(1); keys must be hashable (immutable).
Equal objects must have equal hashes; a mutable key changing hash breaks lookup.
Cryptographic hashes (SHA-256) differ from table hashes: collision-resistance, not speed.
Key points
- Load factor: alpha = n/m (entries / buckets).
- Primary clustering: Long runs of filled slots forming under linear probing.
- Tombstone: Marker for deleted slot in open addressing.
- Separate chaining: Each bucket stores a linked list of keys.
- Linear probing, m=7,
h(k)=k mod 7: insert 15 (1), 22 (1->2), 29 (1->2->3): slots 1,2,3. - Open addressing needs n
<=m; chaining has no such limit.
Read more
Example
CodeChaining table and linear probing:
class ChainedHash:
def __init__(self, m=8):
self.m, self.n = m, 0
self.t = [[] for _ in range(m)]
def put(self, k, v):
b = self.t[hash(k) % self.m]
for i, (kk, _) in enumerate(b):
if kk == k: b[i] = (k, v); return
b.append((k, v)); self.n += 1
if self.n / self.m > 0.75: self._resize()
def get(self, k):
for kk, v in self.t[hash(k) % self.m]:
if kk == k: return v
raise KeyError(k)
def _resize(self):
old = [kv for b in self.t for kv in b]
self.m *= 2; self.t = [[] for _ in range(self.m)]; self.n = 0
for k, v in old: self.put(k, v)
def linear_probe_insert(table, key):
m = len(table); i = key % m
for step in range(m):
j = (i + step) % m
if table[j] is None:
table[j] = key; return j
raise OverflowErrorHashMap Patterns & Two-Sum
A hash map trades O(n) memory for O(1) average lookups, which converts nested loops into a single pass: store what you have seen (value, index, count, prefix sum) and query for the complement or duplicate in constant time.
In short: Remember what you have already seen so you can answer "have I seen the match?" instantly.
Think about it
Single most useful interview tool; many problems are one hash-map insight away from linear time.
Two-sum: for each x look up target - x in a dict of value->index, then insert x (after the lookup to avoid using the same element twice): O(n) time, O(n) space vs O(n^2) brute force; with sorted input two pointers use O(1) space.
Duplicates (contains duplicate): set of seen.
Frequency count: Counter; majority element, top-K frequent, first non-repeating char.
Group anagrams: key = sorted(word) or a 26-count tuple.
Subarray sum equals K: prefix-sum frequency map.
Longest consecutive sequence: put all in a set, start counting only from numbers x where x-1 is absent: O(n).
Longest substring without repeats: char -> last index.
Isomorphic strings / word pattern: two-way mapping.
Intersection of arrays: set lookups.
LRU: hash map + doubly list.
Pitfalls: mutable keys (lists) unhashable in Python (use tuple); worst-case O(n) per operation under adversarial collisions (anti-hash tests) - sort-based or tree-based maps give O(log n) guaranteed; iteration order is insertion order in Python 3.7+ dict but unspecified in a set and in a C++ unordered_map.
Hash set vs map: set stores keys only.
Key points
- Complement lookup: Query target - x instead of scanning for it.
- Frequency map: key
->count of occurrences. - Canonical key: Normalized form (sorted letters) used to group equivalents.
Read more
Example
CodeHash map patterns:
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i # insert AFTER lookup
return []
from collections import defaultdict, Counter
def group_anagrams(words):
g = defaultdict(list)
for w in words:
g[tuple(sorted(w))].append(w)
return list(g.values())
def longest_consecutive(nums):
s, best = set(nums), 0
for x in s:
if x - 1 not in s: # only start of a run
y = x
while y + 1 in s: y += 1
best = max(best, y - x + 1)
return best
def first_unique_char(s):
c = Counter(s)
for i, ch in enumerate(s):
if c[ch] == 1: return i
return -1Solved examples
Table size 10, h(k)=k mod 10, linear probing. Insert 12, 22, 32, 42. Slots?
Positions
Formula Applied:—Approach note: Look at the run: later keys travel farther.
Chaining, m = 7, insert keys 50, 700, 76, 85, 92, 73, 101 with h(k)=k mod 7. Longest chain?
Max chain length
Formula Applied:—Approach note: Compute k mod m carefully; 700 mod 7 = 0.
Two-sum on [3, 3] with target 6: why must lookup happen before insert?
Reasoning
Formula Applied:—Approach note: Input [3] target 6 must return empty.
Hash table size m = 7, keys 10, 20, 15 inserted with h(k)=k mod 7 and chaining. List the chain at slot 1.
Keys in slot 1
Formula Applied:—Approach note: Load factor α = n/m; chaining keeps α flexible.
Real-world applications
Using Hashing & Hash Tables in real projects
Caches, symbol tables, database indexes, deduplication, counting, password storage (with cryptographic hashes).
Common mistakes
❌ Myth: Hash table operations are always O(1).
Why this is wrong: Average O(1) assumes uniform hashing and bounded load factor; adversarial or poor hashes degrade to O(n).
✅ Verified Truth: Average O(1), worst case O(n) (or O(log n) with tree buckets).
⚠️ Exam Tip: Always say average vs worst.
❌ Myth: Using a power of two as table size is fine with k mod m.
Why this is wrong: Only the low bits of k are used, causing clustering for patterned keys.
✅ Verified Truth: Prefer a prime m with the division method (or mix bits first).
⚠️ Exam Tip: GATE: choose prime, not close to a power of 2.
❌ Myth: Deleting from open addressing just clears the slot.
Why this is wrong: It breaks probe chains for keys that probed past that slot.
✅ Verified Truth: Mark as tombstone (DELETED) and treat it as occupied during search.
⚠️ Exam Tip: Mention tombstones whenever asked about deletion.
Revision notes
A hash table maps keys to array indices using a hash function, giving average O(1) insert, search and delete. Collisions are resolved by chaining or open addressing; hash maps/sets turn many O(n^2) scans into O(n).
High-Yield Quick Revision Points
- h(k)=k mod m (prime m); load factor alpha = n/m; resize at ~0.75, amortized O(1)
- Chaining: Theta(1+alpha); open addressing needs alpha<1, tombstones for delete
- Linear: primary clustering; quadratic: secondary; double hashing best
- Two-sum: lookup complement before inserting; prefix-sum map; group by canonical key
- Average O(1), worst O(n)
Practice questions
Load factor of a table with 15 keys and 20 slots:
Which resolves collisions without extra memory outside the table?
Primary clustering is associated with:
Average time of two-sum using a dict:
Expected chain length under simple uniform hashing: