SDE & MLE Prep

138. Copy List with Random Pointer

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]