Programming & DSA
Hashing
Hashing questions are mostly table-fill numericals: apply h(k) = k mod m, resolve collisions with the stated scheme, and know the load-factor formulas; graph representations round out the data-structure choices.
GATE CSE hashing — hash functions, collision resolution by chaining and open addressing (linear, quadratic, double hashing), load factor, rehashing, and adjacency matrix vs adjacency list for graphs, with samples and drills.
Learning outcomes
- Apply division-method hash functions and fill hash tables correctly under chaining and each open-addressing probe rule
- Compute load factor and estimate expected search cost for chaining and open addressing
- Explain clustering, deletion with tombstones, and rehashing, and compare chaining with open addressing
- Compare adjacency matrix and adjacency list representations of a graph by space and operation cost
Hash tables and hash functions
- A hash table stores keys in an array of m slots (buckets). A hash function h maps a key to a slot index in 0 .. m − 1, so insert, search, and delete take O(1) time on average.
- Division method: h(k) = k mod m. Choose m as a prime not close to a power of 2 so that patterns in the keys do not map to a few slots. With m = 10, keys that end in the same digit collide.
- Multiplication method: h(k) = floor(m × (k × A mod 1)) with a constant 0 < A < 1 (such as 0.618...); it is less sensitive to the choice of m. Other methods: mid-square and folding.
- A good hash function is fast, deterministic, and spreads keys uniformly (simple uniform hashing: every key is equally likely to hash to any slot, independent of other keys).
- A collision occurs when two different keys map to the same slot. Because the key universe is larger than m, collisions cannot be avoided in general (pigeonhole principle).
- Hash tables support only equality lookups efficiently; they do not keep keys sorted, so range queries and min/max are O(n) (use a BST instead).
- Worst case: if every key lands in one slot, search degrades to O(n).
Formulas to remember
-
Division: h(k) = k mod m -
Multiplication: h(k) = ⌊m × frac(k × A)⌋ -
Load factor α = n / m (n keys, m slots)
Worked example
Problem. With h(k) = k mod 11, which slot does key 25 map to?
Solution. 25 = 2 × 11 + 3, so the slot is 3.
Collision resolution by chaining
- Separate chaining keeps a linked list in each slot; all keys hashing to slot i are stored in the list T[i]. Insert at the head of the list is O(1) (if duplicates need not be checked); search and delete take time proportional to the chain length.
- With simple uniform hashing the expected chain length is α = n/m. An unsuccessful search costs Θ(1 + α) on average; a successful search costs about 1 + α/2 comparisons.
- Chaining never overflows: α can exceed 1 (more keys than slots), and performance degrades gracefully. If α = O(1) (m proportional to n) all operations are O(1) on average.
- Worst-case search is O(n) when all n keys fall in one chain (or O(log n) if chains are balanced trees).
- Extra memory is needed for the list pointers, and cache behaviour is worse than a plain array.
- Deletion is simple: remove the node from its list.
| Slot | Keys (m = 7, h = k mod 7) |
|---|---|
| 0 | 700 |
| 1 | 50 → 85 → 92 |
| 3 | 73 → 101 |
| 6 | 76 |
Worked example
Problem. Insert 50, 700, 76, 85, 92, 73, 101 into a chained table with m = 7 and h(k) = k mod 7. What is the longest chain?
Solution. 50, 85, and 92 all map to slot 1 (since 49, 84, 91 are multiples of 7), so the longest chain has length 3.
Open addressing: linear, quadratic, and double hashing
- In open addressing every key is stored in the table itself, so n ≤ m (α ≤ 1). On a collision we probe a sequence of slots h(k, 0), h(k, 1), ... until an empty slot is found (insert) or the key/empty slot is found (search).
- Linear probing: h(k, i) = (h′(k) + i) mod m. Simple and cache-friendly but suffers from primary clustering — long runs of occupied slots that grow and make later probes longer.
- Quadratic probing: h(k, i) = (h′(k) + c1 × i + c2 × i²) mod m. It avoids primary clustering but keys with the same initial slot follow the same probe sequence (secondary clustering). It may not reach every slot unless m and the constants are chosen carefully.
- Double hashing: h(k, i) = (h1(k) + i × h2(k)) mod m. Keys get different probe sequences, so clustering is minimal. h2(k) must be non-zero and relatively prime to m (for example, m prime and h2(k) = 1 + (k mod (m − 1))).
- Deletion: simply emptying a slot would break the probe chain of later keys, so deleted slots are marked with a tombstone (DELETED) that search skips and insert may reuse.
- Under uniform hashing the expected number of probes is about 1 / (1 − α) for an unsuccessful search and (1/α) ln(1/(1 − α)) for a successful search. At α = 0.5 these are 2 and about 1.39; at α = 0.9 they are 10 and about 2.56.
- Insertion in a full open-addressed table fails; the table needs resizing before α approaches 1.
| Scheme | Probe sequence | Weakness |
|---|---|---|
| Linear | (h + i) mod m | Primary clustering |
| Quadratic | (h + c1 i + c2 i²) mod m | Secondary clustering |
| Double hashing | (h1 + i × h2) mod m | Needs a good h2; two hash computations |
Worked example
Problem. m = 10, h(k) = k mod 10, linear probing. Insert 22, 32, 42, 12 in this order. Where does 12 go?
Solution. 22 → slot 2; 32 → 2 is full, goes to 3; 42 → 4; 12 → hashes to 2, probes 2, 3, 4 (all full), lands in slot 5.
Load factor, rehashing, and chaining vs open addressing
- Load factor α = n / m controls performance. Chaining works for any α; open addressing needs α < 1 and is usually kept below 0.5–0.7.
- Rehashing: when α crosses a threshold, allocate a bigger table (often about double, rounded to a prime) and reinsert all keys with the new hash function. One rehash costs O(n), but doubling makes the amortised cost O(1) per insertion.
- Chaining: simple deletion, tolerates α > 1, uses extra pointers, less sensitive to the hash function. Open addressing: no pointers and better cache behaviour, but deletion needs tombstones and the performance collapses as α → 1.
- Average-case operations are O(1) for both; worst case O(n) for both (all keys colliding).
- Comparing with other structures: hash tables beat balanced BSTs on average for equality search (O(1) vs O(log n)) but give no ordered traversal.
- GATE favourite: fill a table of m = 7 or 10 slots with the given keys and report which slot a specific key ends up in or how many probes a search takes.
| Feature | Chaining | Open addressing |
|---|---|---|
| Storage | Lists outside the table | Inside the table |
| α limit | Can exceed 1 | At most 1 |
| Deletion | Easy | Needs tombstones |
| Clustering | None | Primary/secondary |
| Extra memory | Pointers per key | None |
Worked example
Problem. A table with m = 20 slots stores n = 15 keys using chaining. What is α and the expected unsuccessful-search cost?
Solution. α = 15/20 = 0.75; the expected cost is about 1 + α = 1.75 probes (average chain length 0.75).
Graph representations: adjacency matrix vs adjacency list
- A graph G = (V, E) with V vertices and E edges can be stored as an adjacency matrix (a V × V array where A[i][j] = 1 (or the edge weight) if there is an edge i → j) or as an adjacency list (an array of V lists, list i holds the neighbours of vertex i).
- Adjacency matrix: space Θ(V²); checking whether edge (u, v) exists is O(1); listing the neighbours of a vertex is O(V); adding or removing an edge is O(1). Best for dense graphs (E close to V²). For an undirected graph the matrix is symmetric and holds 2E ones; the row sum of a vertex is its degree.
- Adjacency list: space Θ(V + E) (an undirected edge appears twice, so 2E list entries); checking an edge is O(deg(u)); listing neighbours is O(deg(u)). Best for sparse graphs.
- BFS and DFS take O(V + E) with adjacency lists but O(V²) with an adjacency matrix, because scanning a row costs O(V).
- Sum of degrees = 2E for an undirected graph; for a directed graph, sum of in-degrees = sum of out-degrees = E.
- Weighted graphs store the weight in the matrix cell or in the list node (with infinity or 0 for no edge in the matrix).
- Adjacency lists are themselves a hash-table-like structure: an array indexed by vertex id (a perfect direct hash) whose slots are chains of neighbours.
| Aspect | Adjacency matrix | Adjacency list |
|---|---|---|
| Space | Θ(V²) | Θ(V + E) |
| Edge (u, v) exists? | O(1) | O(deg u) |
| All neighbours of u | O(V) | O(deg u) |
| BFS / DFS total | O(V²) | O(V + E) |
| Best for | Dense graphs | Sparse graphs |
Worked example
Problem. An undirected graph has V = 1000 and E = 3000. Compare storage.
Solution. Matrix: 1000 × 1000 = 10^6 cells. List: 1000 list heads + 2 × 3000 = 6000 entries (about 7000 units) — far smaller for this sparse graph.
GATE exam tricks — hashing and graph representations
- Table-fill questions: write the m empty slots, insert keys strictly in the given order, and write each computed h(k) next to the key before probing. Never skip the mod step.
- Chaining details to check: are new keys inserted at the head or tail of a chain, and does the question ask for the longest chain, number of empty buckets, or comparisons? Insertion order changes the chain order but not the chain membership.
- Open-addressing formulas (uniform hashing): unsuccessful search about 1 / (1 - alpha) probes; successful search about (1 / alpha) ln(1 / (1 - alpha)). Chaining: unsuccessful about alpha, successful about 1 + alpha / 2 (search cost Theta(1 + alpha)).
- Linear probing suffers primary clustering; quadratic probing suffers secondary clustering (same start gives same sequence) and only guarantees finding a slot if m is prime and alpha <= 1/2; double hashing needs h2(k) != 0 and coprime to m (prime m is the easy way).
- Deletion in open addressing: set a tombstone (DELETED marker), not EMPTY, otherwise later searches stop at the hole and miss keys. Insert may reuse a tombstone but a search must continue past it.
- Counting collisions: with n keys uniformly into m slots the expected number of colliding pairs is C(n, 2) / m, and P(no collision) = m (m-1) ... (m-n+1) / m^n. Birthday paradox: collisions appear far sooner than n = m.
- Rehashing: when alpha crosses a threshold, allocate a larger table (often next prime about 2m) and reinsert every key with the NEW h; positions cannot simply be copied.
- Graph choices: dense graph or frequent edge-existence queries -> matrix; sparse graph or BFS/DFS -> adjacency list. Undirected matrix has 2E ones; undirected list has 2E nodes; row sum = degree.
Worked example
Problem. Double hashing in a table of m = 7: h1(k) = k mod 7, h2(k) = 1 + (k mod 5), probe (h1 + i * h2) mod 7. Insert 10, 17, 24 in order. Which slots do they occupy?
Solution. 10: h1 = 3, slot 3 is free, so slot 3. 17: h1 = 3 is taken; h2 = 1 + (17 mod 5) = 3; next probe (3 + 3) mod 7 = 6, free, so slot 6. 24: h1 = 3 is taken; h2 = 1 + (24 mod 5) = 5; probe (3 + 5) mod 7 = 1, free, so slot 1. Final slots: 10 -> 3, 17 -> 6, 24 -> 1.
Worked trace: chaining table and search cost
- Compute every bucket index first; then group keys by index to read off the chains.
- Number of comparisons for an unsuccessful search in bucket b equals the length of chain b (plus 0 for an empty bucket); for a successful search it is the key position in its chain.
- Average over keys, not over buckets, when the question says "average successful search".
Worked example
Problem. Chaining with h(k) = k mod 7 (append at tail). Insert 50, 700, 76, 85, 92, 73, 101. What is the longest chain, how many buckets are empty, and how many comparisons does a successful search for 92 take?
Solution. Buckets: 50 -> 1, 700 -> 0, 76 -> 6, 85 -> 1, 92 -> 1, 73 -> 3, 101 -> 3. Chains: 0: [700]; 1: [50, 85, 92]; 3: [73, 101]; 6: [76]. Longest chain = 3 (bucket 1). Empty buckets: 2, 4, 5, so 3 are empty. Finding 92 follows 50, 85, 92: 3 comparisons.
Exam tips
- Write the table of m slots first, then insert keys one by one in the given order.
- For linear probing, always probe from h(k) upward with wrap-around modulo m.
- For double hashing, compute h1 and h2 once, then (h1 + i × h2) mod m for i = 1, 2, ...
- Chaining: α can be above 1. Open addressing: α ≤ 1 and 1/(1 − α) is the unsuccessful probe estimate.
- Adjacency matrix: Θ(V²) space and O(1) edge test; list: Θ(V + E) space and O(deg) edge test.
10 GATE-style MCQs for Hashing with full explanations. Attempt each question before revealing the answer.
A hash table with 20 slots stores 15 keys using chaining. The load factor is:
Show answer & explanation
Answer: B
α = n / m = 15 / 20 = 0.75.
A table of 10 slots uses h(k) = k mod 10 with linear probing. After inserting 12, 22, 32 (in this order), how many probes does an unsuccessful search for 42 need (counting every slot examined, including the final empty one)?
Show answer & explanation
Answer: B
12, 22, 32 occupy slots 2, 3, 4. Searching for 42 probes slots 2, 3, 4 (all occupied by other keys) and then slot 5 (empty): 4 probes.
Keys 50, 700, 76, 85, 92, 73, 101 are inserted into a chained hash table of 7 slots with h(k) = k mod 7. The length of the longest chain is:
Show answer & explanation
Answer: B
Slots: 700→0; 50, 85, 92→1; 73, 101→3; 76→6. Slot 1 has three keys.
In the worst case, searching a hash table that uses chaining with n keys takes:
Show answer & explanation
Answer: C
If all keys hash to the same slot they form one chain of length n that must be scanned.
Primary clustering is a problem associated mainly with:
Show answer & explanation
Answer: B
With linear probing, occupied slots form long contiguous runs that keep growing; this is primary clustering.
A table with m = 7 uses double hashing with h1(k) = k mod 7 and h2(k) = 1 + (k mod 5), probe i is (h1 + i × h2) mod 7. If the first slot for key 24 is occupied, which slot is probed next?
Show answer & explanation
Answer: A
h1(24) = 3 and h2(24) = 1 + 4 = 5. For i = 1: (3 + 5) mod 7 = 8 mod 7 = 1.
Assuming uniform hashing with open addressing and load factor α = 0.5, the expected number of probes for an unsuccessful search is about:
Show answer & explanation
Answer: B
Expected probes ≈ 1 / (1 − α) = 1 / 0.5 = 2.
An undirected graph with 5 vertices and 6 edges (no self-loops) is stored as an adjacency matrix. The number of 1 entries is:
Show answer & explanation
Answer: B
Each undirected edge sets two symmetric entries A[i][j] and A[j][i], so there are 2 × 6 = 12 ones.
For a sparse graph with n vertices and O(n) edges, the space needed by the adjacency matrix and by the adjacency list are respectively:
Show answer & explanation
Answer: B
The matrix always needs Θ(n²) cells; the list needs Θ(V + E) = Θ(n) for O(n) edges.
Why is it wrong to simply mark a slot empty when deleting a key from a linear-probing hash table?
Show answer & explanation
Answer: B
A search stops at the first empty slot; if a key later in the probe chain depends on the now-empty slot, it becomes unreachable. A tombstone preserves the chain.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
With h(k) = k mod 11, key 25 hashes to slot:
Show answer & explanation
Answer: B) 3
25 mod 11 = 3.
m = 7, h(k) = k mod 7, linear probing. Keys 8, 15, 22 are inserted in this order. Key 22 is stored in slot:
Show answer & explanation
Answer: C) 3
All three keys have home slot 1. 8 → 1, 15 → 2, 22 → 3.
m = 10, quadratic probing h(k, i) = (k + i²) mod 10. Key 5 is stored. Key 15 is inserted next. It is stored in slot:
Show answer & explanation
Answer: B) 6
i = 0 gives slot 5 (occupied); i = 1 gives (15 + 1) mod 10 = 6, which is free.
Keys 10, 15, 20, 25 are inserted into a chained table with m = 5 and h(k) = k mod 5. The length of the chain at slot 0 is:
Show answer & explanation
Answer: D) 4
All four keys are multiples of 5, so all hash to slot 0.
A directed graph has E edges. The number of 1 entries in its adjacency matrix (no multiple edges) is:
Show answer & explanation
Answer: A) E
Each directed edge sets exactly one entry A[u][v].
The space used by the adjacency list representation of a directed graph with V vertices and E edges is:
Show answer & explanation
Answer: B) Θ(V + E)
One list header per vertex plus one list node per edge.
Which operation is O(1) with an adjacency matrix but O(degree) with an adjacency list?
Show answer & explanation
Answer: B) Checking whether edge (u, v) exists
The matrix cell A[u][v] is accessed directly, whereas the list of u must be scanned.
In an open-addressing hash table with m slots, the load factor can be at most:
Show answer & explanation
Answer: B) 1
Every key occupies its own slot, so n ≤ m.
BFS on a graph with V vertices and E edges stored as adjacency lists runs in time:
Show answer & explanation
Answer: C) O(V + E)
Every vertex is dequeued once and every adjacency list is scanned once.
Under simple uniform hashing, the expected time for a successful search in a chained table with load factor α is:
Show answer & explanation
Answer: A) Θ(1 + α)
About 1 + α/2 comparisons on average, which is Θ(1 + α); it is O(1) when α is a constant.
Topic FAQs
Why should the table size m be a prime number?
A prime m, not close to a power of 2, spreads keys that have regular patterns more evenly under the division method and works well with quadratic and double hashing.
Can the load factor exceed 1?
Yes for chaining (several keys per slot), but never for open addressing, because every key occupies its own slot.
Why use tombstones when deleting in open addressing?
Marking a slot as simply empty would stop later searches too early and make existing keys unreachable; a tombstone keeps the probe chain intact.
When is an adjacency matrix preferred over an adjacency list?
For dense graphs or when constant-time edge tests are needed; for sparse graphs the adjacency list saves space and speeds up traversals.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.