Good afternoon! Here's our prompt for today.
You are given a head
of a linked list of length n
such that each node contains an additional random
pointer. This random
pointer may point to any other node in the list or is null
.
Create a deep copy
of the given linked list, and return its head
such that no additional space is used. The deep copy should consist of exactly n
brand new nodes. Each new node must have the following properties:
- Its value is set to the value of its corresponding original node.
- Both the
next
andrandom
pointers of the new node should point to new nodes in the copied list, such that the pointers in the original list and copied list represent the same list state. - None of the pointers in the new list should point to nodes in the original list.

For example, if there are two nodes X and Y in the original list, where X.random --> Y
, then for the corresponding two nodes x
and y
in the copied list, x.random --> y
.
Constraints
0 <= n <= 1000
104 <= Node.val <= 104
Node.random
isnull
or points to some node in the linked list.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
80
console.log('PASSED: ' + "`cloneRandomList([[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]) should return `[[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]`");
var assert = require('assert');
​
function Node(val, next, random) {
this.val = val;
this.next = next;
this.random = random;
};
​
function cloneRandomList(head) {
// add your code here
return;
}
​
​
try {
let head = new Node(1);
head.next = new Node(2);
head.random = head.next;
head.next.next = null;
head.next.random = head.next;
let lst, random = listToString(head);
let lstAns, randomAns = listToString(cloneRandomList(head));
assert.equal(lst, lstAns);
assert.equal(random, randomAns);
console.log('PASSED: ' + "`cloneRandomList([[1, 1],[2, 1]]) should return `[[1, 1],[2, 1]]`");
} catch (err) {
console.log(err);
}
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?