Copy List With Random Pointer
Deep copy a linked list whose nodes have a random pointer
DSA, Medium, Linked List
Which structure or algorithm, and what does it cost.
A list node holds val, a next link, and an extra random link. The extra link may point at any node in the list, even its own node, or at nothing. Return the head of a deep copy: it has its own nodes, the same values, and the same next and extra links, now between the copies. Do not change the original list. Examples write each node as [val, r], where r is the position (from 0) of its extra link target, or -1 for nothing.
Examples
Constraints
- 0 <= length of the list <= 100,000.
- Each value is a whole number between -1,000,000 and 1,000,000.
- Each random position is -1 or a valid position in the list.
Your answer must contain
- The simple method and why it is slow; the map method with its memory cost; the method with O(1) extra memory; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time. A map gives O(n) extra memory; the best answer needs only O(1).
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Copying the next links is easy. The hard part is a random link, which must point to the copy of its target, not to the original.
Hint 2 the approach
You need to find the copy of any original node at once. Think of a lookup table from each original node to its copy.
Hint 3 the key step
To avoid the table, put each copy right beside its original. Then the copy of a target is the node after that target. Finally split the two lists apart.
Walkthrough
Full walkthrough brute force to best
Brute force
Copy the nodes along the next links first. Then for each original node, walk from the head to find the position of its random target, and walk the same number of steps in the copy to set the copy's random. Each lookup is O(n), so the total is O(n^2) time with O(1) extra memory.
Better method
Use a map from each original node to its copy. Pass one: create every copy and store it in the map. Pass two: for each original, set the copy's next to the map entry of the original's next, and its random to the map entry of the original's random. The time is O(n) and the map uses O(n) memory.
Best method
Remove the map by storing the pairing inside the list. Pass one: after each original node insert its copy, so the list reads A, A', B, B', and so on. Now the copy of any node is simply its next. Pass two: for each original, the copy's random is the next of the original's random, which is the copy of the target. Pass three: pull the copies out into their own list and put the original links back. Every pass is linear, and the only extra nodes are the copies, which the answer needs anyway.
Hand trace
Run on [[6, 2], [3, 3], [8, -1], [5, 0]]. Call the originals A, B, C, D, with random targets C, D, none, A. After pass one the list is A, A', B, B', C, C', D, D'. Pass two: A'.random is the node after C, so C'. B'.random is D'. C has no random. D'.random is A'. Pass three: take out A', B', C', D' and restore the next links of A, B, C, D. The copy has values 6, 3, 8, 5 and random targets at positions 2, 3, none, 0, which matches the input.
Code
class Node:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
def copy_random_list(head):
node = head
while node: # 1. put a copy right after each original
node.next = Node(node.val, node.next)
node = node.next.next
node = head
while node: # 2. a copy's random is the copy after the original's random
if node.random:
node.next.random = node.random.next
node = node.next.next
dummy = Node(0)
tail, node = dummy, head
while node: # 3. split the copies out and restore the originals
tail.next = node.next
tail = tail.next
node.next = tail.next
node = node.next
return dummy.nextTime and memory
O(n) time: three linear passes. O(1) extra memory besides the copied nodes. The map version has the same time and O(n) extra memory.
Common mistakes
- Pointing a copy's random at the original node. The copy must point at another copy.
- Setting random links while the copies are not all created yet. Create every copy first.
- Forgetting to restore the original list. After the split, each original must point to its old next again.
- Not checking for a null random pointer before reading the node after it.