Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the array that will store the buckets for the HashMap.
DSA Java
private Entry<K, V>[] [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic name like 'elements' instead of 'buckets'.
Confusing the array with a list of entries.
✗ Incorrect
The array that stores the linked list heads in the HashMap is commonly named 'buckets'.
2fill in blank
mediumComplete the code to compute the index for a key in the buckets array.
DSA Java
int index = (key.hashCode() & 0x7fffffff) [1] buckets.length;
Attempts:
3 left
💡 Hint
Common Mistakes
Using division '/' which gives a quotient, not an index.
Using multiplication '*' which can exceed array bounds.
✗ Incorrect
The modulo operator '%' is used to ensure the index fits within the array length.
3fill in blank
hardFix the error in the put method to correctly add a new entry at the head of the linked list.
DSA Java
Entry<K, V> newEntry = new Entry<>(key, value, [1]);
buckets[index] = newEntry;Attempts:
3 left
💡 Hint
Common Mistakes
Setting next to null loses the existing entries.
Setting next to newEntry causes a cycle.
✗ Incorrect
The new entry's next pointer should point to the current head at buckets[index].
4fill in blank
hardFill both blanks to complete the get method that searches for a key in the linked list.
DSA Java
for (Entry<K, V> e = buckets[index]; e != [1]; e = e.[2]) { if (e.key.equals(key)) { return e.value; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using buckets[index] in the loop condition causes infinite loop.
Using 'value' instead of 'next' to move to next entry.
✗ Incorrect
The loop continues until e is null, moving to the next entry via e.next.
5fill in blank
hardFill all three blanks to complete the remove method that deletes an entry by key.
DSA Java
Entry<K, V> prev = null; for (Entry<K, V> e = buckets[index]; e != null; e = e.[1]) { if (e.key.equals(key)) { if (prev == null) { buckets[index] = e.[2]; } else { prev.[3] = e.[2]; } return e.value; } prev = e; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' instead of 'next' for traversal or link update.
Using 'prev' instead of 'next' for link update.
✗ Incorrect
Use 'next' to traverse and update links; prev.next skips the removed entry.
