Skip to main content

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.

~4 hrs ~1–1.5 marks · High 10 samples · 10 practice · 10 cards

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.
SlotKeys (m = 7, h = k mod 7)
0700
150 → 85 → 92
373 → 101
676

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.

Hash table with 7 buckets using h(k) = k mod 7 where colliding keys form linked chains
Same-bucket keys sit on a chain; alpha = n / m can exceed 1.

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.
SchemeProbe sequenceWeakness
Linear(h + i) mod mPrimary clustering
Quadratic(h + c1 i + c2 i²) mod mSecondary clustering
Double hashing(h1 + i × h2) mod mNeeds 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.

Linear probing table of size 7 showing keys 10, 17, 24, 3 and 31 filling slots with wrap-around
Collisions walk to the next free slot (wrapping mod m) — watch the primary cluster grow.

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.
FeatureChainingOpen addressing
StorageLists outside the tableInside the table
α limitCan exceed 1At most 1
DeletionEasyNeeds tombstones
ClusteringNonePrimary/secondary
Extra memoryPointers per keyNone

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.
AspectAdjacency matrixAdjacency list
SpaceΘ(V²)Θ(V + E)
Edge (u, v) exists?O(1)O(deg u)
All neighbours of uO(V)O(deg u)
BFS / DFS totalO(V²)O(V + E)
Best forDense graphsSparse 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.

Small undirected graph drawn with its adjacency list and 4 by 4 adjacency matrix
Matrix: O(V^2) space, O(1) edge test. List: O(V + E) space, O(deg) neighbour scan.

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.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Hashing with full explanations. Attempt each question before revealing the answer.

Q1 Load factor

A hash table with 20 slots stores 15 keys using chaining. The load factor is:

  • A) 0.25
  • B) 0.75
  • C) 1.33
  • D) 15
Show answer & explanation

Answer: B

α = n / m = 15 / 20 = 0.75.

Q2 Linear probing

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)?

  • A) 3
  • B) 4
  • C) 5
  • D) 1
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.

Q3 Chaining

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:

  • A) 2
  • B) 3
  • C) 4
  • D) 5
Show answer & explanation

Answer: B

Slots: 700→0; 50, 85, 92→1; 73, 101→3; 76→6. Slot 1 has three keys.

Q4 Worst case

In the worst case, searching a hash table that uses chaining with n keys takes:

  • A) O(1)
  • B) O(log n)
  • C) O(n)
  • D) O(n log n)
Show answer & explanation

Answer: C

If all keys hash to the same slot they form one chain of length n that must be scanned.

Q5 Clustering

Primary clustering is a problem associated mainly with:

  • A) Double hashing
  • B) Linear probing
  • C) Separate chaining
  • D) Universal hashing
Show answer & explanation

Answer: B

With linear probing, occupied slots form long contiguous runs that keep growing; this is primary clustering.

Q6 Double hashing

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?

  • A) 1
  • B) 4
  • C) 5
  • D) 2
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.

Q7 Open addressing analysis

Assuming uniform hashing with open addressing and load factor α = 0.5, the expected number of probes for an unsuccessful search is about:

  • A) 1
  • B) 2
  • C) 4
  • D) 10
Show answer & explanation

Answer: B

Expected probes ≈ 1 / (1 − α) = 1 / 0.5 = 2.

Q8 Adjacency matrix

An undirected graph with 5 vertices and 6 edges (no self-loops) is stored as an adjacency matrix. The number of 1 entries is:

  • A) 6
  • B) 12
  • C) 25
  • D) 30
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.

Q9 Graph representation

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:

  • A) O(n) and O(n²)
  • B) O(n²) and O(n)
  • C) O(n²) and O(n²)
  • D) O(n) and O(n)
Show answer & explanation

Answer: B

The matrix always needs Θ(n²) cells; the list needs Θ(V + E) = Θ(n) for O(n) edges.

Q10 Deletion

Why is it wrong to simply mark a slot empty when deleting a key from a linear-probing hash table?

  • A) It would increase the load factor
  • B) It can break the probe sequence so that keys inserted later in that chain cannot be found
  • C) It makes the hash function invalid
  • D) Nothing; it is the standard method
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.

Topic drill · 10 questions

10 practice questions — Hashing

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

With h(k) = k mod 11, key 25 hashes to slot:

  • A) 2
  • B) 3
  • C) 4
  • D) 14
Show answer & explanation

Answer: B) 3

25 mod 11 = 3.

P2

m = 7, h(k) = k mod 7, linear probing. Keys 8, 15, 22 are inserted in this order. Key 22 is stored in slot:

  • A) 1
  • B) 2
  • C) 3
  • D) 4
Show answer & explanation

Answer: C) 3

All three keys have home slot 1. 8 → 1, 15 → 2, 22 → 3.

P3

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:

  • A) 5
  • B) 6
  • C) 9
  • D) 1
Show answer & explanation

Answer: B) 6

i = 0 gives slot 5 (occupied); i = 1 gives (15 + 1) mod 10 = 6, which is free.

P4

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:

  • A) 1
  • B) 2
  • C) 3
  • D) 4
Show answer & explanation

Answer: D) 4

All four keys are multiples of 5, so all hash to slot 0.

P5

A directed graph has E edges. The number of 1 entries in its adjacency matrix (no multiple edges) is:

  • A) E
  • B) 2E
  • C) E/2
  • D) V
Show answer & explanation

Answer: A) E

Each directed edge sets exactly one entry A[u][v].

P6

The space used by the adjacency list representation of a directed graph with V vertices and E edges is:

  • A) Θ(V²)
  • B) Θ(V + E)
  • C) Θ(E²)
  • D) Θ(V × E)
Show answer & explanation

Answer: B) Θ(V + E)

One list header per vertex plus one list node per edge.

P7

Which operation is O(1) with an adjacency matrix but O(degree) with an adjacency list?

  • A) Listing all neighbours of a vertex
  • B) Checking whether edge (u, v) exists
  • C) Counting vertices
  • D) Running BFS
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.

P8

In an open-addressing hash table with m slots, the load factor can be at most:

  • A) 0.5
  • B) 1
  • C) 2
  • D) Unlimited
Show answer & explanation

Answer: B) 1

Every key occupies its own slot, so n ≤ m.

P9

BFS on a graph with V vertices and E edges stored as adjacency lists runs in time:

  • A) O(V)
  • B) O(E)
  • C) O(V + E)
  • D) O(V²)
Show answer & explanation

Answer: C) O(V + E)

Every vertex is dequeued once and every adjacency list is scanned once.

P10

Under simple uniform hashing, the expected time for a successful search in a chained table with load factor α is:

  • A) Θ(1 + α)
  • B) Θ(n)
  • C) Θ(log n)
  • D) Θ(α²)
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.

Quick revision · 10 cards

10 flashcards — Hashing

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What is a hash function and what properties should a good hash function have?
Q2 What is the load factor of a hash table and how is it computed?
Q3 How does separate chaining resolve collisions in a hash table?
Q4 How does linear probing find a slot for a key whose home slot is occupied?
Q5 Why does quadratic probing reduce primary clustering but still suffer from secondary clustering?
Q6 What is the probe sequence formula for double hashing?
Q7 What is the expected cost of an unsuccessful search in a chained hash table under simple uniform hashing?
Q8 Why is a prime number often chosen as the table size for the division method?
Q9 How do adjacency matrix and adjacency list representations of a graph differ in space?
Q10 When is rehashing performed and what does it do?