Copy List with Random Pointer

Pattern: Copy with random pointer

medium

Weave a copy right after each original node, so the copy of any node x is x.next. Then each copy's random is its original's random's next. Finally unweave the two lists, restoring the original.

The problem

Each node of a linked list has a value, a next pointer and a random pointer that points to any node of the list or is null. Return a deep copy: brand-new nodes with the same values, whose next and random pointers point to the corresponding new nodes. No pointer in the copy may point into the original list. For example, the list written as [[7, -1], [13, 0], [11, 4], [10, 2], [1, 0]] (value and random index for each node) copies to the same picture.

The function name copyRandomList matches LeetCode. Use the link above for the exact statement and limits. In this guide's code the node type is RNode. The tests print the copy in the same form and check that it shares no node with the original.

Think first

  • Copying next is easy. Why is random harder?
  • For any original node, how could you find its copy in O(1)?
  • Can you do that without a hash map?

Hints

    Brute force, and why it fails

    For each node, find its random target's position by walking from the head, then walk the copy to the same position: O(n²). A hash map makes it O(n) time with O(n) memory. Weaving makes it O(n) time with O(1) extra memory.

    The key insight

    The hard part is a lookup from an original node to its copy. Weaving stores that lookup in the list itself: every copy sits right after its original.

    Dry run

    70 
    131 
    112 
    103 
    14 

    The list is 7 → 13 → 11 → 10 → 1. The randoms are none, 7, 1, 11 and 7 (as indexes -1, 0, 4, 2, 0).

    Step 1 of 4

    The plan

    for each original x: insert new node(x.val) after x
    for each original x: if x.random: x.next.random = x.random.next
    dummy, tail = new node
    for each original x:
        c = x.next
        x.next = c.next
        tail.next = c; tail = c
    return dummy.next
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Three passes. Apart from the copy itself, only a few pointers are used.

    Edge cases

    • Empty list: null.
    • A node whose random points to itself: its copy's random points to the copy.
    • Equal values: nodes are told apart by position, not value.
    I've built my logic, show the code

    Java

    class Solution {
        public RNode copyRandomList(RNode head) {
            for (RNode cur = head; cur != null; cur = cur.next.next) {   // 1. put a copy right after each node
                RNode copy = new RNode(cur.val);
                copy.next = cur.next;
                cur.next = copy;
            }
            for (RNode cur = head; cur != null; cur = cur.next.next) {   // 2. a copy's random is the copy of the random
                if (cur.random != null) cur.next.random = cur.random.next;
            }
            RNode dummy = new RNode(0), tail = dummy;
            for (RNode cur = head; cur != null; cur = cur.next) {        // 3. pull the copies out, restore the original
                RNode copy = cur.next;
                cur.next = copy.next;
                tail.next = copy;
                tail = copy;
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        RNode* copyRandomList(RNode* head) {
            for (RNode* cur = head; cur != NULL; cur = cur->next->next) {   // 1. put a copy right after each node
                RNode* copy = new RNode(cur->val);
                copy->next = cur->next;
                cur->next = copy;
            }
            for (RNode* cur = head; cur != NULL; cur = cur->next->next) {   // 2. copy's random = copy of the random
                if (cur->random != NULL) cur->next->random = cur->random->next;
            }
            RNode dummy(0);
            RNode* tail = &dummy;
            for (RNode* cur = head; cur != NULL; cur = cur->next) {         // 3. pull the copies out, restore the original
                RNode* copy = cur->next;
                cur->next = copy->next;
                tail->next = copy;
                tail = copy;
            }
            return dummy.next;
        }
    };

    Python

    from lib import RNode
    
    class Solution:
        def copyRandomList(self, head: RNode) -> RNode:
            cur = head
            while cur is not None:                  # 1. put a copy right after each node
                cur.next = RNode(cur.val, cur.next)
                cur = cur.next.next
            cur = head
            while cur is not None:                  # 2. a copy's random is the copy of the random
                if cur.random is not None:
                    cur.next.random = cur.random.next
                cur = cur.next.next
            dummy = tail = RNode(0)
            cur = head
            while cur is not None:                  # 3. pull the copies out, restore the original
                copy = cur.next
                cur.next = copy.next
                tail.next = copy
                tail = copy
                cur = cur.next
            return dummy.next

    Common mistakes

    • Pointing a copy's random at the original target.
    • Forgetting to restore the original's next pointers.
    • Stepping one node at a time in the woven list instead of two.

    Similar problems