138. Copy List with Random Pointer
Asked at 19Meta78Amazon69Microsoft56Bloomberg55Google38Nvidia64CVENT100oyo88Wix87Arista Networks78Morgan Stanley77Intel76Snowflake59Walmart Labs53Uber52Oracle45Adobe44Flipkart43TikTok26
Problem
Each node of a linked list has a next pointer and a random pointer to any node of the list (or null). Return a deep copy: new nodes whose next and random pointers mirror the original structure, never pointing into the original list.
Example: [[7,null],[13,0],[11,4],[10,2],[1,0]] (value, index the random pointer targets) → an identical, independent list
Map each original node → its clone (first pass), then wire next/random through the map (second pass). O(1)-space variant: interleave clones A A' B B' …, set A'.random = A.random.next, then unweave.
Complexity: O(n) time, O(n) space.
class Node: # provided by LeetCode
def __init__(self, x: int, next: "Node" = None, random: "Node" = None):
self.val, self.next, self.random = int(x), next, random
class Solution:
def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
clone = {None: None}
cur = head
while cur:
clone[cur] = Node(cur.val)
cur = cur.next
cur = head
while cur:
clone[cur].next = clone[cur.next]
clone[cur].random = clone[cur.random]
cur = cur.next
return clone[head]
spec = [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]
nodes = [Node(v) for v, _ in spec]
for i, (_, r) in enumerate(spec):
nodes[i].next = nodes[i + 1] if i + 1 < len(nodes) else None
nodes[i].random = nodes[r] if r is not None else None
c, out = Solution().copyRandomList(nodes[0]), []
copies = []
while c:
assert c not in nodes
copies.append(c); c = c.next
assert [[n.val, copies.index(n.random) if n.random else None] for n in copies] == spec
class Node { // provided by LeetCode
int val; Node next, random;
Node(int val) { this.val = val; }
}
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> clone = new HashMap<>();
for (Node cur = head; cur != null; cur = cur.next) clone.put(cur, new Node(cur.val));
for (Node cur = head; cur != null; cur = cur.next) {
clone.get(cur).next = clone.get(cur.next); // get(null) -> null
clone.get(cur).random = clone.get(cur.random);
}
return clone.get(head);
}
}
type Node struct { // provided by LeetCode
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
clone := map[*Node]*Node{nil: nil}
for cur := head; cur != nil; cur = cur.Next {
clone[cur] = &Node{Val: cur.Val}
}
for cur := head; cur != nil; cur = cur.Next {
clone[cur].Next = clone[cur.Next]
clone[cur].Random = clone[cur.Random]
}
return clone[head]
}