Start learning free

LESSON 437 OF 673 · LINKED LISTS

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

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 None.

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 None means no node.

Your function gets only head.

 

Example 1:

4 9 1 6 null next random
Input: values = [4,9,1,6], random = [None,3,0,2]
Output: values = [4,9,1,6], random = [None,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 None,
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 = [None,0]
Output: values = [8,8], random = [None,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 None), return None.
  • Each value is from -10,000 to 10,000.
  • Each random is None 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

    PYTHON · LINKED LISTS

    Copy List Random Pointer in Python, 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 nodes with 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, cloning complex objects, etc.

    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.
    2. Assigning random pointers: Set the random pointers of the new nodes using the interwoven structure.
    3. Restoring the original list and extracting the copied list: Separate the interwoven list into the original and the copied list.

    Algorithm

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

    1. Traverse the original list and create new nodes. Insert each new node right after its corresponding original node.
    2. Traverse the interwoven list and set the random pointers for the new nodes. If the original node's random pointer points to a node, the new node's random pointer should point to the node right after the original node's random pointer.
    3. Separate the interwoven list into the original list and the copied list by adjusting the next pointers.

    Code Implementation

    class Node:
        def __init__(self, val: int, next: 'Node' = None, random: 'Node' = None):
            self.val = val
            self.next = next
            self.random = random
    
    def copyRandomList(head: 'Node') -> 'Node':
        if not head:
            return None
    
        # Step 1: Create new nodes and interweave them with the original nodes
        current = head
        while current:
            new_node = Node(current.val, current.next)
            current.next = new_node
            current = new_node.next
    
        # Step 2: Assign random pointers to the new nodes
        current = head
        while current:
            if current.random:
                current.next.random = current.random.next
            current = current.next.next
    
        # Step 3: Separate the interwoven list into original and copied lists
        current = head
        new_head = head.next
        while current:
            new_node = current.next
            current.next = new_node.next
            if new_node.next:
                new_node.next = new_node.next.next
            current = current.next
    
        return new_head
    

    Complexity Analysis

    The time complexity of this algorithm is O(n) because we traverse 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): The function should return null.
    • A list with only one node: The function should correctly handle the random pointer, whether it is null or points to itself.

    Testing

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

    def test_copyRandomList():
        # Test case 1: Empty list
        assert copyRandomList(None) == None
    
        # Test case 2: Single node with no random pointer
        node1 = Node(1)
        assert copyRandomList(node1).val == 1
    
        # Test case 3: Single node with random pointer to itself
        node1.random = node1
        copied = copyRandomList(node1)
        assert copied.val == 1
        assert copied.random == copied
    
        # Test case 4: Multiple nodes with random pointers
        node1 = Node(1)
        node2 = Node(2)
        node1.next = node2
        node1.random = node2
        node2.random = node2
        copied = copyRandomList(node1)
        assert copied.val == 1
        assert copied.random.val == 2
        assert copied.next.val == 2
        assert copied.next.random.val == 2
    
    test_copyRandomList()
    

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller, manageable steps.
    • Think about how to maintain the relationships between nodes while creating new nodes.
    • Use diagrams to visualize the list structure and the changes you need to make.

    Conclusion

    Understanding and solving the "Copy List with Random Pointer" problem helps in mastering deep copy concepts and linked list manipulations. Practice similar problems to improve your problem-solving skills.

    Additional Resources

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