A hash function h defined h(key)=key mod 7, with linear probing, is used to…
20182021
A hash function h defined h(key)=key mod 7, with linear probing, is used to insert the keys 44, 45, 79, 55, 91, 18, 63 into a table indexed from 0 to 6. What will be the location of key 18 ?
Answer: C. 5 — Concept In open addressing, a hash function fixes only a key’s home slot: h(key) = key mod m, where m is the number of slots. Nothing guarantees that home…
- A.
3
- B.
4
- C.
5
- D.
6
Attempted by 442 students.
Show answer & explanation
Correct answer: C
Concept
In open addressing, a hash function fixes only a key’s home slot: h(key) = key mod m, where m is the number of slots. Nothing guarantees that home slot is free.
Linear probing resolves a collision by scanning forward one slot at a time — (h(key) + 1) mod m, then (h(key) + 2) mod m, and so on, wrapping past the last slot back to slot 0 — and storing the key in the first free slot it meets.
So a key’s home slot depends only on its own value, but its final resting slot also depends on which slots the earlier insertions already took. Insertion order is part of the answer.
Application
Here m = 7, so h(key) = key mod 7 and the slots are 0 to 6. Insert the keys in the order given, tracking occupancy as you go.
44 mod 7 = 2. Slot 2 is free, so 44 is stored at slot 2.
45 mod 7 = 3. Slot 3 is free, so 45 is stored at slot 3.
79 mod 7 = 2. Slot 2 holds 44, so probe forward: slot 3 holds 45, slot 4 is free. 79 is stored at slot 4.
55 mod 7 = 6. Slot 6 is free, so 55 is stored at slot 6.
91 mod 7 = 0. Slot 0 is free, so 91 is stored at slot 0.
18 mod 7 = 4. Slot 4 holds 79, so probe forward: slot 5 is free. 18 is stored at slot 5.
63 mod 7 = 0. Slot 0 holds 91, so probe forward: slot 1 is free. 63 is stored at slot 1.
The table after all seven insertions:
Slot | Key stored |
|---|---|
0 | 91 |
1 | 63 |
2 | 44 |
3 | 45 |
4 | 79 |
5 | 18 |
6 | 55 |
Cross-check
Search for 18 the same way you inserted it: start at h(18) = 4, find 79 there, step forward to slot 5 and find 18. A successful search retraces the insertion path, which confirms the placement.
Contrast this with the order-free reading: 18 hashes to slot 4, and had 18 been inserted before 79, slot 4 would indeed have been its final home. The same key lands in a different slot purely because 79 arrived first — which is exactly why linear probing must be traced in insertion order.
Key 18 is stored at slot 5.
A video solution is available for this question — log in and enroll to watch it.