Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node with the same value as the original node.
DSA Java
Node copy = new Node([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using head.next instead of head.val
Using head.random instead of head.val
Using the whole head node instead of its value
✗ Incorrect
We create a new node with the value of the original node, which is head.val.
2fill in blank
mediumComplete the code to insert the copied node right after the original node.
DSA Java
copy.next = [1].next; [1].next = copy;
Attempts:
3 left
💡 Hint
Common Mistakes
Using copy instead of head to access next
Setting pointers in the wrong order
Using head.next.next instead of head.next
✗ Incorrect
We set copy.next to head.next, then set head.next to copy to insert copy after head.
3fill in blank
hardFix the error in setting the random pointer of the copied node.
DSA Java
if (head.random != null) { head.next.random = head.random[1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting random to head.random instead of head.random.next
Using .random or .val instead of .next
Not checking if head.random is null
✗ Incorrect
The copied node's random pointer should point to the copied version of head.random, which is head.random.next.
4fill in blank
hardComplete the code to restore the original list and extract the copied list.
DSA Java
Node original = head; Node copy = head.next; Node copyHead = copy; while (original != null) { original.next = original.next[1]; copy.next = copy.next; original = original.next; copy = copy.next; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting original.next to original.next instead of original.next.next
Setting copy.next incorrectly causing cycles
Not updating original and copy pointers properly
✗ Incorrect
To restore the original list, set original.next to original.next.next. To link copied nodes, set copy.next to copy.next (empty string means no change if copy.next is null).
5fill in blank
hardFill all three blanks to complete the clone function that returns the copied list head.
DSA Java
public Node copyRandomList(Node head) {
if (head == null) return null;
Node curr = head;
while (curr != null) {
Node copy = new Node([1]);
copy.next = curr.next;
curr.next = copy;
curr = copy.next;
}
curr = head;
while (curr != null) {
if (curr.random != null) {
curr.next.random = curr.random[2];
}
curr = curr.next.next;
}
curr = head;
Node copyHead = head.next;
Node copyCurr = copyHead;
while (curr != null) {
curr.next = curr.next[3];
if (copyCurr.next != null) {
copyCurr.next = copyCurr.next.next;
}
curr = curr.next;
copyCurr = copyCurr.next;
}
return copyHead;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using curr.random instead of curr.random.next
Not restoring original list correctly
Incorrectly linking copied nodes
✗ Incorrect
We create a copy node with curr.val, set random pointer to curr.random.next, and restore original list by setting curr.next to curr.next.next.
