Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node in the linked list for chaining.
DSA Java
class Node { int key; int value; Node next; Node(int key, int value) { this.key = key; this.value = value; this.next = [1]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting next to 'this' causes a self-loop.
Using 'new Node()' without parameters causes a compile error.
Assigning next to 'head' before linking is incorrect.
✗ Incorrect
When creating a new node, its next pointer should be null initially because it does not point to any other node yet.
2fill in blank
mediumComplete the code to compute the hash index for a given key.
DSA Java
int getIndex(int key) {
return key [1] size;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '/' returns a quotient, not an index.
Using '*' or '-' does not limit the index within array bounds.
✗ Incorrect
The modulo operator '%' is used to ensure the index stays within the array size.
3fill in blank
hardFix the error in the insert method to correctly add a new node at the beginning of the chain.
DSA Java
void insert(int key, int value) {
int index = getIndex(key);
Node newNode = new Node(key, value);
newNode.next = [1];
table[index] = newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting next to null breaks the chain.
Setting next to newNode causes a self-loop.
Using 'table' without index is invalid.
✗ Incorrect
The new node's next should point to the current head of the chain at that index before updating the head.
4fill in blank
hardFill both blanks to complete the search method that finds a value by key in the chain.
DSA Java
int search(int key) {
int index = getIndex(key);
Node current = table[[1]];
while (current != null) {
if (current.key [2] key) {
return current.value;
}
current = current.next;
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' causes wrong search logic.
Accessing table with 'key' instead of 'index' causes errors.
✗ Incorrect
We start at the chain head at 'index' and check if current.key equals the search key.
5fill in blank
hardFill all three blanks to complete the delete method that removes a node by key from the chain.
DSA Java
void delete(int key) {
int index = getIndex(key);
Node current = table[index];
Node prev = null;
while (current != null) {
if (current.key [1] key) {
if (prev == null) {
table[index] = current.[2];
} else {
prev.[3] = current.next;
}
return;
}
prev = current;
current = current.next;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' for link updates.
Using '!=' instead of '==' in the if condition.
Not updating table[index] when deleting the first node.
✗ Incorrect
We check if current.key equals key, then update links: if deleting head, update table[index] to current.next; else link prev.next to current.next.
