Description

Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

Return the head of the copied linked list.

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.

Your code will only be given the head of the original linked list.

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]]

Example 3:

Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]

Constraints:

  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
  • Node.random is null or is pointing to some node in the linked list.

Approach - Hash Map 2 Passes

  • In first loop we create new nodes and create a hash map to store the original node as key and new created copy node as value so as to access easily especially for random pointer
  • add a key and value for null so as to cover the case for the pointer pointing to null
  • In second loop we use hash map to locate our copied node then assign next and random based on it
  • There exists other solutions too with better complexities but this seems very simple will check those later
  • Time:O(n) Space: O(n)
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;
 
    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
 
class Solution {
    public Node copyRandomList(Node head) {
        Map<Node, Node> copy = new HashMap<>();
        copy.put(null,null);
        Node curr = head;
    
        while (curr != null) {
            copy.put(curr, new Node(curr.val));
            curr = curr.next;
        }
 
        curr = head;
        while (curr != null) {
            Node node = copy.get(curr);
            node.next = copy.get(curr.next);
            node.random = copy.get(curr.random);
            curr = curr.next;
        }
 
        return copy.get(head);
    }
}

Approach 1: HashMap (Brute Force / Intuitive)

Intuition

When creating new nodes, you cannot immediately set their random pointers because the target node might not have been created yet. Using a Hash Map acts as a lookup table mapping Original Node -> Cloned Node.

  1. Pass 1: Traverse the list, create a new clone node for every original node, and save map.put(curr, new Node(curr.val)).
  2. Pass 2: Traverse again and wire up next and random pointers using map lookups (map.get(curr).next = map.get(curr.next) and map.get(curr).random = map.get(curr.random)).
class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        
        Map<Node, Node> map = new HashMap<>();
        
        // Pass 1: Create clone nodes and store mapping
        Node curr = head;
        while (curr != null) {
            map.put(curr, new Node(curr.val));
            curr = curr.next;
        }
        
        // Pass 2: Connect next and random pointers for each cloned node
        curr = head;
        while (curr != null) {
            map.get(curr).next = map.get(curr.next);
            map.get(curr).random = map.get(curr.random);
            curr = curr.next;
        }
        
        return map.get(head);
    }
}
 
  • Time Complexity: — 2 passes through the list.
  • Space Complexity: — auxiliary space for storing entries in the HashMap.

Approach 2: Interweaving Nodes (Most Optimized Extra Space)

Intuition

Instead of an external HashMap to store Original -> Clone, interleave each cloned node directly after its original node inside the list:

Because is placed right next to , the clone of any node is always . So the clone’s random pointer () is simply .

3 Simple Steps

  1. Interleave: Create clones and insert them right after their originals ().
  2. Connect Randoms: Set curr.next.random = curr.random.next (if curr.random != null).
  3. Separate Lists: Unweave the original list and the cloned list to restore the original state and isolate the output.
class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        
        // Step 1: Interleave cloned nodes (A -> A' -> B -> B')
        Node curr = head;
        while (curr != null) {
            Node clone = new Node(curr.val);
            clone.next = curr.next;
            curr.next = clone;
            curr = clone.next;
        }
        
        // Step 2: Assign random pointers for cloned nodes
        curr = head;
        while (curr != null) {
            if (curr.random != null) {
                curr.next.random = curr.random.next; //point to clone random not original random
            }
            curr = curr.next.next;
        }
        
        // Step 3: Separate original list and cloned list
        curr = head;
        Node cloneHead = head.next;
        while (curr != null) {
            Node clone = curr.next;
            curr.next = clone.next;
            if (clone.next != null) {
                clone.next = clone.next.next;
            }
            curr = curr.next;
        }
        
        return cloneHead;
    }
}
 
  • Time Complexity: — 3 linear passes through the list.
  • Space Complexity: — auxiliary space (modifying pointers in-place).

Quick Memory Cheat Sheet

  • HashMap: “Store Old -> New in a map. Pass 1 creates nodes, Pass 2 hooks up next and random via map lookups.”
  • Interweaving: “Place New right behind Old (curr.next = clone). Cloned random is just curr.random.next. Restore original list pointers at the end.”