Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the hash index for a given key.
DSA C++
int hashFunction(int key, int size) {
return key [1] size;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using division (/) instead of modulo (%) causes wrong index calculation.
✗ Incorrect
The modulo operator (%) is used to ensure the hash index stays within the table size.
2fill in blank
mediumComplete the code to perform linear probing by moving to the next index.
DSA C++
int linearProbe(int index, int size) {
return (index [1] 1) % size;
}Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting 1 moves backward, which is incorrect for linear probing.
✗ Incorrect
Adding 1 moves to the next slot; modulo keeps it within table size.
3fill in blank
hardFix the error in the insertion loop to correctly handle collisions using linear probing.
DSA C++
void insert(int table[], int size, int key) {
int index = hashFunction(key, size);
while (table[index] != -1) {
index = (index [1] 1) % size;
}
table[index] = key;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction causes infinite loops or wrong probing sequence.
✗ Incorrect
We add 1 to index to move to the next slot during collision resolution.
4fill in blank
hardFill both blanks to complete the search function using linear probing.
DSA C++
int search(int table[], int size, int key) {
int index = hashFunction(key, size);
int start = index;
while (table[index] != key) {
index = (index [1] 1) % size;
if (index == [2]) return -1;
}
return index;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing index to size instead of start causes incorrect termination.
✗ Incorrect
We increment index by 1 and check if we returned to the start index to stop searching.
5fill in blank
hardFill all three blanks to complete the deletion function using linear probing.
DSA C++
void deleteKey(int table[], int size, int key) {
int index = hashFunction(key, size);
int start = index;
while (table[index] != key) {
index = (index [1] 1) % size;
if (index == [2]) return; // Key not found
}
table[index] = [3]; // Mark slot as empty
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong sentinel value instead of -1 causes search errors.
✗ Incorrect
Increment index by 1, stop if back to start, and mark slot as -1 to indicate empty.
