Start learning free

LESSON 435 OF 671 · LINKED LISTS

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

Practice O(n) Read the full explanation

You get the head of a linked list. Build a deep copy of it and return the copy's head.

Each node has a value, a next pointer and one more pointer, random. This random pointer can lead to any node of the list, even the node itself. It can also be null.

The copy is made only of new nodes, one for each original node, with the same values. In the copy, each next and random leads to the matching new node. Nothing points back into the original list.

Say an original node's random leads to the third node. Then its copy's random leads to the copy of the third node.

The examples describe the list with two arrays of the same length. The first, values, holds the values from the head on. The second, random, holds one entry per node. For node i, random[i] is the index of the node its random leads to. Indexes start at 0, and null means no node.

Your function gets only head.

 

Example 1:

4 9 1 6 null next random
Input: values = [4,9,1,6], random = [null,3,0,2]
Output: values = [4,9,1,6], random = [null,3,0,2]
Explanation: The dashed blue arrows are the random pointers.
The copy has four new nodes with the same links:
the new 4's random is null,
the new 9's random leads to the new 6,
the new 1's random leads to the new 4,
the new 6's random leads to the new 1.

Example 2:

8 8 null next random
Input: values = [8,8], random = [null,0]
Output: values = [8,8], random = [null,0]
Explanation: Both nodes hold 8.
The second 8's random leads to the first 8.
In the copy, it must lead to the new first 8, not the old one.

Example 3:

7 next random

Input: values = [7], random = [0]
Output: values = [7], random = [0]
Explanation: The only node's random leads to itself.
In the copy, the new node's random leads to the new node.

 

Constraints:

  • 0 to 1,000 nodes.
  • For an empty list (head is null), return null.
  • Each value is from -10,000 to 10,000.
  • Each random is null or leads to a node of the same list.

Note:

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


STEP 1 OF 11
    Ctrl + Enter to check

    JAVASCRIPT · LINKED LISTS

    Copy List Random Pointer in JavaScript, explained

    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:

    • An empty list (head is null).
    • A list with only one node where the random pointer is null or points to itself.
    • A list where all random pointers are null.

    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:

    • Simple lists with a few nodes and various random pointer configurations.
    • Edge cases as mentioned above.
    • Large lists to ensure the algorithm handles the upper constraint efficiently.

    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

    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free