Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a new key into the hash table using chaining.
DSA C++
void insert(int key) {
int index = key % TABLE_SIZE;
table[index].[1](key);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop_back removes elements instead of adding.
Using clear deletes all elements.
Using size returns the number of elements, not insertion.
✗ Incorrect
We use push_back to add the key to the linked list at the computed index.
2fill in blank
mediumComplete the code to search for a key in the hash table using chaining.
DSA C++
bool search(int key) {
int index = key % TABLE_SIZE;
for (int i = 0; i < table[index].size(); i++) {
if (table[index][i] [1] key) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != will check for inequality, which is incorrect here.
Using > or < does not check for equality.
✗ Incorrect
We check if the current element equals the key to find it.
3fill in blank
hardFix the error in the code to delete a key from the hash table using chaining.
DSA C++
void remove(int key) {
int index = key % TABLE_SIZE;
for (auto it = table[index].begin(); it != table[index].end(); ++it) {
if (*it [1] key) {
table[index].erase(it);
break;
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != will erase the wrong elements.
Using > or < does not correctly identify the key.
✗ Incorrect
We must check if the element pointed by iterator equals the key to erase it.
4fill in blank
hardFill both blanks to correctly initialize the hash table and insert keys using chaining.
DSA C++
#define TABLE_SIZE 10 std::vector<int> table[[1]]; void insert(int key) { int index = key % [2]; table[index].push_back(key); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different size for the array and modulo causes errors.
Using 'key' as size or modulo is incorrect.
✗ Incorrect
The table size is 10, and the modulo operation uses TABLE_SIZE to find the index.
5fill in blank
hardFill all three blanks to implement a function that prints all keys in the hash table using chaining.
DSA C++
void printTable() {
for (int i = 0; i < [1]; i++) {
std::cout << "Bucket " << i << ": ";
for (auto [2] : table[i]) {
std::cout << [3] << " -> ";
}
std::cout << "null\n";
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i' as the inner loop variable causes confusion.
Printing the wrong variable instead of the key.
✗ Incorrect
We loop from 0 to TABLE_SIZE, use 'k' as the loop variable for elements, and print 'k'.
