Start learning free

LESSON 399 OF 634 · LINKED LISTS

Copy List with Random Pointer II in C++ (O(n) Time, O(1) Space)

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 O(1) extra space.


STEP 1 OF 22
    Ctrl + Enter to check

    C++ · LINKED LISTS

    Copy List Random Pointer in C++, 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: For each node in the original list, create a new node and insert it right after the original node. This way, the new nodes are interleaved with the original nodes.
    2. Assigning random pointers: Iterate through the interleaved list and assign the random pointers for the new nodes.
    3. Restoring the original list and extracting the copied list: Separate the interleaved list into the original list and the copied 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 interleaved list and set the random pointers for the new nodes.
    3. Separate the interleaved list into the original list and the copied list.

    Code Implementation

    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* next;
        Node* random;
    
        Node(int _val) {
            val = _val;
            next = nullptr;
            random = nullptr;
        }
    };
    
    class Solution {
    public:
        Node* copyRandomList(Node* head) {
            if (!head) return nullptr;
    
            // Step 1: Create new nodes and interleave them with original nodes
            Node* curr = head;
            while (curr) {
                Node* newNode = new Node(curr->val);
                newNode->next = curr->next;
                curr->next = newNode;
                curr = newNode->next;
            }
    
            // Step 2: Assign random pointers for the new nodes
            curr = head;
            while (curr) {
                if (curr->random) {
                    curr->next->random = curr->random->next;
                }
                curr = curr->next->next;
            }
    
            // Step 3: Separate the interleaved list into original and copied lists
            Node* newHead = head->next;
            curr = head;
            while (curr) {
                Node* temp = curr->next;
                curr->next = temp->next;
                if (temp->next) {
                    temp->next = temp->next->next;
                }
                curr = curr->next;
            }
    
            return newHead;
        }
    };
    

    Complexity Analysis

    The time complexity of this approach is O(n) because we iterate through the list a constant number of times. The space complexity is O(1) extra space because we are not using any additional data structures that grow with the input size.

    Edge Cases

    Some potential edge cases include:

    • An empty list (head is null).
    • A list where all random pointers are null.
    • A list where random pointers form a cycle.

    Each of these cases is handled by the algorithm as it does not make any assumptions about the structure of the random pointers.

    Testing

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

    • Simple list with no random pointers.
    • List with random pointers pointing to previous nodes.
    • List with random pointers forming a cycle.
    • Empty list.

    Using a variety of test cases ensures that the solution handles all possible scenarios.

    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 original structure while creating the new structure.
    • Consider edge cases and how your solution handles them.
    • Practice similar problems to improve your problem-solving skills.

    Conclusion

    In this blog post, we discussed how to create a deep copy of a linked list with random pointers in C++. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in computer science.

    Additional Resources

    For further reading and practice, consider the following resources:

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