← Back to Leo Academy Masterclass

Problem #138: Copy List with Random Pointer

Medium Linked List

Intuition & Strategy Breakdown

Use a two-pass algorithm with hash map (or 3-pass interleave copy). Copy nodes and map original node to cloned node, then update next and random pointers.

Python Solution

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if not head:
            return None
        
        # Pass 1: Interleave nodes
        curr = head
        while curr:
            new_node = Node(curr.val, curr.next)
            curr.next = new_node
            curr = new_node.next
            
        # Pass 2: Set random pointers
        curr = head
        while curr:
            if curr.random:
                curr.next.random = curr.random.next
            curr = curr.next.next
            
        # Pass 3: Extract copy list
        curr = head
        copy_head = head.next
        while curr:
            copy = curr.next
            curr.next = copy.next
            if copy.next:
                copy.next = copy.next.next
            curr = curr.next
            
        return copy_head

Java Solution

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        
        // Pass 1: Interleave
        Node curr = head;
        while (curr != null) {
            Node next = curr.next;
            curr.next = new Node(curr.val);
            curr.next.next = next;
            curr = next;
        }
        
        // Pass 2: Set randoms
        curr = head;
        while (curr != null) {
            if (curr.random != null) {
                curr.next.random = curr.random.next;
            }
            curr = curr.next.next;
        }
        
        // Pass 3: Separate
        curr = head;
        Node copyHead = head.next;
        while (curr != null) {
            Node copy = curr.next;
            curr.next = copy.next;
            if (copy.next != null) {
                copy.next = copy.next.next;
            }
            curr = curr.next;
        }
        return copyHead;
    }
}
Watch Interactive Video on Leo Academy Main App