A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

O(n) time, O(n) extra space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/

public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, RandomListNode> oldToNew = new HashMap<>();
RandomListNode cur = head;
while (cur != null) {
oldToNew.put(cur, new RandomListNode(cur.label));
cur = cur.next;
}
cur = head;
while (cur != null) {
oldToNew.get(cur).next = oldToNew.get(cur.next);
oldToNew.get(cur).random = oldToNew.get(cur.random);
cur = cur.next;
}
return oldToNew.get(head);
}
}

O(n) time, O(1) extra space

Except the space needed for the new list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode cur = head, next, prev;
// copy the nodes one by one, into the old new
// old-new-old-new-old-new...
while (cur != null) {
next = cur.next;
cur.next = new RandomListNode(cur.label);
cur.next.next = next;
cur = next;
}
// copy random node
cur = head;
while (cur != null) {
if (cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
// split new nodes from old ones
RandomListNode newHead = new RandomListNode(0);
prev = newHead;
while (head != null) {
prev.next = head.next;
head.next = head.next.next;
head = head.next;
prev = prev.next;
}
return newHead.next;
}
}

Recursive solution with a global variable

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
Map<RandomListNode, RandomListNode> oldToNew = new HashMap<>();
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
if (oldToNew.containsKey(head)) return oldToNew.get(head);
RandomListNode result = new RandomListNode(head.label);
oldToNew.put(head, result);
result.next = copyRandomList(head.next);
result.random = copyRandomList(head.random);
return result;
}
}