Copy List with Random pointer


138. Copy List with Random Pointer – LeetCode


Problem Statement

A linked list is given where each node contains two pointers:

You must create a deep copy of the list.
Each node in the new list should have the same value and random pointer configuration but be entirely independent from the original list.


Examples

Example 1:

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2:

Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Constraints


Intuition

To copy the list with random pointers:


Approach: Interleaving Nodes (O(1) space)

  1. Interleave cloned nodes between original nodes.

  2. Assign random pointers using original.random.next.

  3. Separate the two lists into original and cloned.


Java Code

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;

        // Step 1: Interleave copied nodes
        Node curr = head;
        while (curr != null) {
            Node copy = new Node(curr.val);
            copy.next = curr.next;
            curr.next = copy;
            curr = copy.next;
        }

        // Step 2: Assign random pointers
        Node orig = head;
        while (orig != null) {
            if (orig.random != null) {
                orig.next.random = orig.random.next;
            }
            orig = orig.next.next;
        }

        // Step 3: Detach copied list from original
        Node dummy = head.next;
        Node copyCurr = dummy;
        orig = head;
        while (orig != null) {
            orig.next = orig.next.next;
            if (copyCurr.next != null) {
                copyCurr.next = copyCurr.next.next;
            }
            orig = orig.next;
            copyCurr = copyCurr.next;
        }

        return dummy;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation No extra data structures, only pointer manipulations

Dry Run

Input:

1 → 2 → 3 → null
random: 1→3, 2→1, 3→2

Step 1:
Create interleaved list:

1 → 1' → 2 → 2' → 3 → 3'

Step 2:
Assign randoms:
1'.random = 3' (original 1's random → 3 → 3')
2'.random = 1'
3'.random = 2'

Step 3:
Split the lists.


Conclusion

This elegant O(1) space solution is a powerful trick in linked list cloning.
By interleaving and detaching, we avoid extra space while maintaining clean node relationships.