Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the buckets array in the HashMap constructor.
DSA Javascript
class HashMap { constructor(size) { this.size = size; this.buckets = new Array([1]).fill(null).map(() => []); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or null as the array length causes an empty buckets array.
Using undefined causes an error.
✗ Incorrect
The buckets array should have the length equal to the given size to store key-value pairs.
2fill in blank
mediumComplete the hash function to compute the index for a given key.
DSA Javascript
hash(key) {
let hash = 0;
for (let char of key) {
hash += char.charCodeAt(0);
}
return hash [1] this.size;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using * or + causes index out of range errors.
Using - can produce negative indices.
✗ Incorrect
The modulo operator (%) ensures the hash value fits within the buckets array size.
3fill in blank
hardFix the error in the set method to correctly update existing keys.
DSA Javascript
set(key, value) {
const index = this.hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket[i][1] = [1];
return;
}
}
bucket.push([key, value]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning key instead of value causes wrong data stored.
Assigning index or bucket causes errors.
✗ Incorrect
To update the value of an existing key, assign the new value to bucket[i][1].
4fill in blank
hardFill both blanks to complete the get method that retrieves a value by key.
DSA Javascript
get(key) {
const index = this.hash(key);
const bucket = this.buckets[index];
for (let [1] = 0; [2] < bucket.length; [1]++) {
if (bucket[[1]][0] === key) {
return bucket[[1]][1];
}
}
return null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for initialization and condition causes errors.
Using index as loop variable conflicts with bucket index.
✗ Incorrect
The loop variable i is used consistently to iterate over the bucket array.
5fill in blank
hardFill all three blanks to complete the remove method that deletes a key-value pair.
DSA Javascript
remove(key) {
const index = this.hash(key);
const bucket = this.buckets[index];
for (let [1] = 0; [2] < bucket.length; [1]++) {
if (bucket[[1]][0] === key) {
bucket.[3]([1], 1);
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using slice instead of splice does not remove elements.
Using different variables for loop causes errors.
✗ Incorrect
Use i as the loop variable and splice to remove the element at index i.
