Copy List with Random Pointer in O(n) Time Complexity using JavaScript


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

Example 4:

Input: head = []
Output: []
Explanation: The given linked list is empty (null pointer), so return null.

 

Constraints:

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

Note:

Your algorithm should run in O(n) time and use at most O(n) extra space.


Understanding the Problem

The core challenge of this problem is to create a deep copy of a linked list where each node has an additional random pointer. The deep copy should be a completely new list with no shared references to the original list. This problem is significant in scenarios where data structures need to be duplicated without affecting the original structure, such as in undo operations, version control systems, or cloning complex objects.

Approach

To solve this problem, we can use a three-step approach:

  1. Interweaving the original list with copied nodes: Create new nodes and insert them right next to their corresponding original nodes. This helps in easily setting up the random pointers in the next step.
  2. Setting up the random pointers: Iterate through the interwoven list and set the random pointers for the copied nodes using the original nodes' random pointers.
  3. Separating the copied list from the original list: Extract the copied nodes to form the new deep copied list and restore the original list.

Algorithm

Let's break down the algorithm step-by-step:

  1. Iterate through the original list and create new nodes. Insert each new node right after its corresponding original node.
  2. Iterate through the interwoven list again to set the random pointers for the copied nodes.
  3. Separate the copied nodes to form the new list and restore the original list.

Code Implementation


// Definition for a Node.
function Node(val, next, random) {
    this.val = val;
    this.next = next;
    this.random = random;
}

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function(head) {
    if (!head) return null;

    // Step 1: Create new nodes and interweave them with the original nodes
    let current = head;
    while (current) {
        let newNode = new Node(current.val, current.next, null);
        current.next = newNode;
        current = newNode.next;
    }

    // Step 2: Set the random pointers for the new nodes
    current = head;
    while (current) {
        if (current.random) {
            current.next.random = current.random.next;
        }
        current = current.next.next;
    }

    // Step 3: Separate the new nodes to form the copied list
    current = head;
    let newHead = head.next;
    while (current) {
        let newNode = current.next;
        current.next = newNode.next;
        if (newNode.next) {
            newNode.next = newNode.next.next;
        }
        current = current.next;
    }

    return newHead;
};

Complexity Analysis

The time complexity of this algorithm is O(n) because we iterate through the list a constant number of times. The space complexity is also O(n) due to the space required for the new nodes.

Edge Cases

Consider the following edge cases:

These cases are handled by the algorithm as it checks for null pointers and correctly sets up the new list.

Testing

To test the solution comprehensively, consider the following test cases:

Thinking and Problem-Solving Tips

When approaching such problems, consider breaking down the problem into smaller, manageable steps. Visualize the data structure and how the pointers need to be set up. Practice similar problems to improve your understanding of linked lists and deep copying techniques.

Conclusion

In this blog post, we discussed how to create a deep copy of a linked list with random pointers in O(n) time complexity using JavaScript. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for mastering data structures and algorithms.

Additional Resources