9.5Exam Practice
Hashing: exam questions and answers
This page is the exam practice for the hashing section. University exams ask about hashing in a few recurring ways: computing hash values, placing a sequence of keys into a table with linear probing, quadratic probing or double hashing, drawing a chained table, deletion and the deleted marker, the load factor and the expected number of probes, growing the table, and reading and writing short code. Here you get original questions of each kind with step-by-step answers.
- How to place a sequence of keys into a table with the three probing methods and with chaining, without mistakes
- How to answer questions on deletion, the load factor, clustering and rehashing, with the reasons
- How to write short code with a hash set and a dictionary, and compare hash tables with other structures
1Concepts and hash functions
The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams, homework and exercise sheets of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. For insertion questions, writing h(k) for each key and then every cell you try, in order, is the safest way. Unless stated otherwise the table size is M = 11 and h(k) = k % 11; the names in the code match the lessons on open addressing and chaining.
1The keys are 10, 20, 30, 40, 50 and 60. With the division method, which cells do they land in for a table size of M = 10 and of M = 11? Why is the table size chosen to be prime?Midterm · concept
| Key | k % 10 | k % 11 |
|---|---|---|
| 10 | 0 | 10 |
| 20 | 0 | 9 |
| 30 | 0 | 8 |
| 40 | 0 | 7 |
| 50 | 0 | 6 |
| 60 | 0 | 5 |
With M = 10 all six keys land in cell 0; the rest of the table stays empty and every operation runs in one cluster. With M = 11 the six keys spread over six different cells.
k % M looks only at the remainder of the key divided by M. If the keys follow a pattern that shares a factor with M (here they are all multiples of 10), the remainders pile up on a few values. A prime M shares no factor with such patterns in real data. A prime M is also needed so that the step size in double hashing can reach every cell. See The division method.
2Compute the following: (a) h(100) and h(101) with the multiplication method, m = 16, A = 0.6180339887; (b) folding in groups of three for the key 2024105317 (from the left, the last three digits of the sum); (c) mid-square for 4321 (the 4th and 5th of the 8 digits of the square).Midterm · trace
With the multiplication method h(k) = ⌊m · frac(k · A)⌋. The fraction is what is left after the whole part of the number is dropped.
| Step | k = 100 | k = 101 |
|---|---|---|
| k · A | 61.8033... | 62.4214... |
| Fraction | 0.8033... | 0.4214... |
| 16 · fraction | 12.85 | 6.74 |
| h(k) | 12 | 6 |
Folding: 202 + 410 + 531 + 7 = 1150, last three digits 150. Mid-square: 4321² = 18671041; the 4th and 5th of the eight digits are 7 and 1, so 71. Two consecutive keys (100 and 101) landing far apart with the multiplication method shows that it spreads keys well. See Multiplication, folding and mid-square.
3Compute two hashes with M = 11 for the words "KAR" and "ARK": (a) the sum of the character codes, (b) a polynomial hash with base 31 (with Horner's method, taking the remainder at each step). Character codes: A = 65, K = 75, R = 82.Midterm · trace
The sum is 75 + 65 + 82 = 222 for both words, and 222 % 11 = 2. Every word made of the same letters lands in the same cell; a sum does not see the order of the letters.
| Step | "KAR" | "ARK" |
|---|---|---|
| 1st letter | 75 % 11 = 9 | 65 % 11 = 10 |
| 2nd letter | (9 · 31 + 65) % 11 = 344 % 11 = 3 | (10 · 31 + 82) % 11 = 392 % 11 = 7 |
| 3rd letter | (3 · 31 + 82) % 11 = 175 % 11 = 10 | (7 · 31 + 75) % 11 = 292 % 11 = 6 |
In a polynomial hash every letter is multiplied by a different power of 31 depending on its position, so "KAR" lands in 10 and "ARK" in 6. Taking the remainder at each step does not change the result but keeps the number from overflowing. See String keys.
2Insertion with open addressing
4Insert the keys 20, 33, 46, 17, 31, 9, 44, 55 in that order into an empty table with linear probing. Draw the final table and write the cells tried for each key. What is the average number of probes?Midterm · trace
With linear probing the i-th probe is cell (h + i) % 11; the key is written into the first empty cell. The search wraps from the end of the table back to the start.
| Key | h(k) | Cells tried | Place | Probes |
|---|---|---|---|---|
| 20 | 9 | 9 | 9 | 1 |
| 33 | 0 | 0 | 0 | 1 |
| 46 | 2 | 2 | 2 | 1 |
| 17 | 6 | 6 | 6 | 1 |
| 31 | 9 | 9, 10 | 10 | 2 |
| 9 | 9 | 9, 10, 0, 1 | 1 | 4 |
| 44 | 0 | 0, 1, 2, 3 | 3 | 4 |
| 55 | 0 | 0, 1, 2, 3, 4 | 4 | 5 |
In total 1 + 1 + 1 + 1 + 2 + 4 + 4 + 5 = 19 probes, 19 / 8 ≈ 2.38 on average. Cells 9, 10, 0, 1, 2, 3 and 4 became one long cluster: 44 and 55, which hash to 0, had to pass through the cluster built by 9, which hashes to 9. This is the primary clustering of linear probing.
5Insert the same keys (20, 33, 46, 17, 31, 9, 44, 55) with quadratic probing. The i-th probe is (h + i²) % 11.Midterm · trace
| Key | h(k) | Cells tried | Place | Probes |
|---|---|---|---|---|
| 20 | 9 | 9 | 9 | 1 |
| 33 | 0 | 0 | 0 | 1 |
| 46 | 2 | 2 | 2 | 1 |
| 17 | 6 | 6 | 6 | 1 |
| 31 | 9 | 9, 10 | 10 | 2 |
| 9 | 9 | 9, 10, (9 + 4) % 11 = 2, (9 + 9) % 11 = 7 | 7 | 4 |
| 44 | 0 | 0, 1 | 1 | 2 |
| 55 | 0 | 0, 1, 4 | 4 | 3 |
In total 15 probes, 15 / 8 ≈ 1.88 on average. The probes jump 1, 4, 9 steps away, so 9 leapt to 7 instead of walking through the cluster, and 44 and 55 found a place sooner. But keys with the same home cell still follow the same sequence: 44 and 55 both try 0, 1, 4, ... This is called secondary clustering. See Quadratic probing.
6Insert the same keys with double hashing: h1(k) = k % 11, h2(k) = 7 − (k % 7), the i-th probe is (h1 + i · h2) % 11.Final · trace
| Key | h1 | h2 | Cells tried | Place | Probes |
|---|---|---|---|---|---|
| 20 | 9 | 1 | 9 | 9 | 1 |
| 33 | 0 | 2 | 0 | 0 | 1 |
| 46 | 2 | 3 | 2 | 2 | 1 |
| 17 | 6 | 4 | 6 | 6 | 1 |
| 31 | 9 | 4 | 9, 2, 6, 10 | 10 | 4 |
| 9 | 9 | 5 | 9, 3 | 3 | 2 |
| 44 | 0 | 5 | 0, 5 | 5 | 2 |
| 55 | 0 | 1 | 0, 1 | 1 | 2 |
In total 14 probes, 1.75 on average: the best of the three methods. 44 and 55 share a home cell (0), but their steps differ (5 and 1), so they followed different paths; secondary clustering is gone. h2 is never 0 (it is between 1 and 7), and since M is prime every step size reaches every cell. See Double hashing.
7In a table with M = 11, cells 0, 1, 3, 4, 5 and 9 are full; fewer than half of the cells are empty. Can a key with h(k) = 0 (for example 22) be inserted with quadratic probing?Final · concept
No. The probes are cells 0, 1, 4, 9, 16 % 11 = 5, 25 % 11 = 3, 36 % 11 = 3, 5, 9, 4, 1, ... i² % 11 only takes the values 0, 1, 3, 4, 5 and 9; those six cells are full, so the insertion never finds an empty cell even though 2, 6, 7, 8 and 10 are empty.
The known result is this: if M is prime and the table is at least half empty, quadratic probing always finds an empty cell. Once the load factor goes past 0.5 that guarantee is gone; that is why tables with quadratic probing are grown at α ≤ 0.5.
8In the table built with linear probing (question 4), 9 is deleted first. (a) If deletion makes the cell EMPTY, what does a search for 44 return? (b) With a deleted marker, which cells does a search for 44 look at? (c) If 66 is inserted next, where does it go?Final · trace
- (a) 44's home cell is 0. Cell 0 holds 33, so the search goes on; cell 1 is EMPTY, so it stops and returns -1. But 44 is in cell 3: the path is broken.
- (b) 0 (33), 1 (deleted marker: skip and go on), 2 (46), 3 (44 found). Four cells.
- (c) 66 % 11 = 0. First the code checks that 66 is not in the table: 0, 1 (marker), 2, 3, 4 are full and not 66, 5 is EMPTY and the search stops. The first usable cell seen on the way is the deleted marker in 1; 66 is written there.
A deleted marker counts as full for searching and as empty for inserting. See Delete: the deleted marker.
3Chaining and rehashing
9Insert the same keys (20, 33, 46, 17, 31, 9, 44, 55) with chaining (a new key goes to the head of its chain). Draw the table. What are the load factor and the longest chain? How many nodes does a search for 42 look at?Midterm · trace
33, 44 and 55 arrived in bucket 0 in that order; since each goes to the head, the chain is 55, 44, 33. Bucket 9's chain is 9, 31, 20. The load factor is α = 8 / 11 ≈ 0.73; the longest chain has 3 nodes.
42 % 11 = 9. All three nodes of bucket 9 (9, 31, 20) are looked at and NULL is reached: an unsuccessful search, 3 nodes. Unlike the clusters of open addressing, the keys of other buckets are never looked at.
10A chained table with m = 5 holds 12, 7, 22, 3, 18 and 9. The threshold is α > 1, so the table is grown. What is the new size and which bucket does each key go to?Midterm · trace
α = 6 / 5 = 1.2 > 1. The new size is the first prime larger than twice the old one: the first prime above 2 · 5 = 10 is 11. Every key's bucket is computed again for the new size:
| Key | Old bucket (k % 5) | New bucket (k % 11) |
|---|---|---|
| 12 | 2 | 1 |
| 7 | 2 | 7 |
| 22 | 2 | 0 |
| 3 | 3 | 3 |
| 18 | 3 | 7 |
| 9 | 4 | 9 |
12, 7 and 22 used to share a bucket and are now in three different ones. 7 and 18, on the other hand, were apart and now share a bucket. The new α = 6 / 11 ≈ 0.55. Copying keys under their old bucket numbers is wrong: if 12 stayed in bucket 2, search(12) would look in bucket 1 and not find it. See Rehashing.
4Code reading
11What does the C function below compute on a chained table? What does it return for the table of question 9? What is its complexity?Midterm · code reading
int mystery(struct HashTable* t) { int best = 0; for (int i = 0; i < M; i++) { int s = 0; for (struct Node* p = t->buckets[i]; p != NULL; p = p->next) s++; if (s > best) best = s; } return best;}It counts the nodes in every bucket's chain and keeps the largest count: it returns the length of the longest chain. In the table of question 9 the chains of buckets 0 and 9 have 3 nodes, so the result is 3.
Every bucket is looked at once and every node once: O(M + n). The value tells how many nodes the worst search in the table looks at; it is used to measure how evenly the hash function spreads the keys.
12The Python method below searches a table with linear probing. In which case does it never finish? Fix it.Final · code reading
def search(self, key): i = key % M while self.items[i] != EMPTY: if self.items[i] == key: return i i = (i + 1) % M return -1The loop stops only at an EMPTY cell. If every cell in the table is full or marked deleted and the key is not there, an EMPTY cell is never reached and the loop runs forever. This really happens in tables that have no empty cells left after many deletions.
The fix: look at most at M cells; if the key was not found after M probes, it is not there.
def search(self, key): i = key % M for _ in range(M): # at most M cells if self.items[i] == EMPTY: return -1 if self.items[i] == key: return i i = (i + 1) % M return -1 # the whole table was walked5Code writing
13Write a Java method that finds, in O(n) average time, whether an integer array has two elements whose sum equals a target.Midterm · code writing
For every x its partner is target - x. The array is walked once; if the partner was seen before, the answer is yes, otherwise x is added to the set.
boolean twoSum(int[] arr, int target) { java.util.HashSet<Integer> seen = new java.util.HashSet<>(); for (int x : arr) { if (seen.contains(target - x)) // its partner was seen before return true; seen.add(x); } return false;}Checking first and adding afterwards stops an element from pairing with itself: for [5] and a target of 10 the answer is not a false yes. For each element contains and add take O(1) on average, so O(n) time and O(n) extra memory in total. The same question with nested loops takes O(n²). See Counting and finding duplicates.
14Write a Python function that checks with a dictionary, in O(n), whether two words are anagrams of each other (the same letters, the same number of times).Final · code writing
def is_anagram(a, b): if len(a) != len(b): return False counter = {} for ch in a: counter[ch] = counter.get(ch, 0) + 1 for ch in b: if counter.get(ch, 0) == 0: # an extra letter in b return False counter[ch] -= 1 return TrueThe letters of the first word are counted and every letter of the second word is taken off the counter. If a letter with a zero count shows up, the second word has an extra letter. Since the lengths are equal, every count is zero at the end. Example: is_anagram("kar", "ark") is true, is_anagram("kara", "arka") is true, is_anagram("kara", "arkk") is false. Sorting and comparing also works but takes O(n log n).
15Write a Python function that prints every key of a chained table in increasing order. Why is it not O(n)?Final · code writing
def print_sorted(t): keys = [] for i in range(M): # every bucket d = t.buckets[i] while d is not None: # the whole chain keys.append(d.data) d = d.next for k in sorted(keys): # O(n log n) print(k, end=" ")A hash table does not keep its keys in order: the hash function deliberately spreads nearby keys into distant buckets. So the keys are first gathered (O(M + n)), then sorted (O(n log n)). If ordered traversal, the minimum, the maximum or the keys in a range are needed often, a binary search tree or a balanced tree is the better structure.
6Complexity and comparison
16A table with M = 11 holds 8 keys. Assuming the keys are spread evenly, how many cells or nodes does an unsuccessful search look at on average: (a) with linear probing, (b) with chaining? How large must the table be (a prime) for α ≤ 0.5?Midterm · complexity
α = 8 / 11 ≈ 0.727.
| Method | Formula | Result |
|---|---|---|
| Linear probing, unsuccessful | ½ (1 + 1 / (1 − α)²) | ≈ 7.2 |
| Linear probing, successful | ½ (1 + 1 / (1 − α)) | ≈ 2.3 |
| Chaining, unsuccessful | 1 + α | ≈ 1.73 |
| Chaining, successful | 1 + α / 2 | ≈ 1.36 |
For α ≤ 0.5 we need M ≥ 8 / 0.5 = 16; the first prime greater than or equal to 16 is 17. Then α = 8 / 17 ≈ 0.47 and an unsuccessful search with linear probing drops to ≈ 2.3 cells. See Open addressing or chaining?.
17What are primary and secondary clustering? Which of linear probing, quadratic probing, double hashing and chaining suffers from which?Final · concept
- Primary clustering: filled cells forming long contiguous blocks. A key that lands anywhere in a block is added at its end and the block grows further; keys from different home cells block each other's way too.
- Secondary clustering: keys with the same home cell always following the same probe sequence. Even without contiguous blocks, the keys of one home cell wait on each other.
| Method | Primary | Secondary |
|---|---|---|
| Linear probing | Yes | Yes |
| Quadratic probing | No | Yes |
| Double hashing | No | No |
| Chaining | No | No (a chain grows but does not affect other buckets) |
The average probe counts in questions 4, 5 and 6 (2.38, 1.88, 1.75) show this order on a small scale.
18Compare a hash table and a balanced binary search tree on search, insertion, deletion, the minimum, ordered traversal and the worst case. When would you pick the tree?Final · comparison
| Operation | Hash table | Balanced BST |
|---|---|---|
| Search, insert, delete (average) | O(1) | O(log n) |
| Search, insert, delete (worst) | O(n) | O(log n) |
| Minimum, maximum | O(M + n) | O(log n) |
| Ordered traversal | O(n log n): must sort first | O(n) |
| Range query (between a and b) | The whole table | O(log n + number of results) |
| Extra requirement | A good hash function | Comparable keys |
If all you need is "is it there, insert, delete", a hash table is faster. If you need operations that depend on order (ordered traversal, minimum, ranges), a worst-case guarantee, or resistance to hostile input, pick a balanced tree. The choice between HashMap and TreeMap in Java is exactly this.
7Try it
M = 11 with linear probing: 3, 14 and 25 are inserted in that order into an empty table. Which cell does 25 go to?
The answer is C. All three hash to 3. 3 settles in 3, 14 in the next cell (4), and 25 in 5 because 3 and 4 are taken.
Show the answer
The answer is C. All three hash to 3. 3 settles in 3, 14 in the next cell (4), and 25 in 5 because 3 and 4 are taken.
Why is h2(k) = 7 − (k % 7) chosen in double hashing?
The answer is A. k % 7 is between 0 and 6; subtracting it from 7 leaves a step between 1 and 7. With a step of 0 every probe would look at the same cell.
Show the answer
The answer is A. k % 7 is between 0 and 6; subtracting it from 7 leaves a step between 1 and 7. With a step of 0 every probe would look at the same cell.
A chained table has M = 11 and n = 22. What is the average chain length?
The answer is B. The average chain length is the load factor: α = n / M = 22 / 11 = 2.
Show the answer
The answer is B. The average chain length is the load factor: α = n / M = 22 / 11 = 2.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.