Copy List with Random Pointer

Make a full copy of a linked list whose nodes also point to a random node, without a lookup map.

A linked list is a chain of nodes, where each node holds a value and a next pointer to the node after it. In this list, each node also has a random pointer, which can point to any node of the list, to the node itself, or to null.

Given the first node, head, make a deep copy and return its first node. A deep copy is a list of brand-new nodes with the same values, whose next and random pointers follow the same pattern but lead only to new nodes. The examples write each node as [value, position of the node its random points to], counting from 0.

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

The Idea

Copying an ordinary linked list is a short walk: for each node, create a new node with the same value and hang it after the previous new node. The random pointers are what make this problem harder.

Take Example 2. It has two nodes, 1 and 2. The random of node 1 points at position 1, which is node 2, and the random of node 2 points at node 2 itself. Write the copy of node 1 as 1' and the copy of node 2 as 2'. The copy must have 1'.random pointing at 2', not at the old node 2.

Now walk the list in order. When we create 1', the node 2' does not exist yet, so we cannot set 1'.random. Even later, once 2' exists, all that node 1 tells us is "my random is node 2". How do we get from an original node to its copy?

One way is to keep a table from each original node to its copy. A neater way needs no table: put each copy into the list itself, right after its original. Look at the picture below.

Top row, the original list: 1 then 2, with the random of 1 pointing at 2 and the random of 2 pointing at itself. Bottom row, each copy woven in right after its original: 1, 1', 2, 2'. Since 1.random is 2, the copy 1' gets 1.random.next, which is 2'.

The top row, labelled "original list", is Example 2, with its random pointers drawn dashed. In the bottom row, each copy is woven in right after its original, so the list reads 1, 1', 2, 2'. The dashed arrow still shows 1.random going to node 2.

Follow it one step further: the node after 2 is 2', exactly the node that 1'.random needs. That is the orange arrow, 1'.random = 1.random.next = 2'. In this woven list, the copy of any original node X is simply X.next. Once every copy has its random, we pull the two lists apart again.

Solution Approach

Turning that idea into code means settling three things: how to reach each node's copy, where the copies' random pointers come from, and how to take the woven list apart again. A table from each node to its copy is the simplest start, and it shows what the weaving saves.

Reaching each node's copy

What is the simplest way to go from an original node to its copy? A HashMap from each original node to its copy. One pass over the list creates every copy and stores it in the map. A second pass visits each original node n again and sets its copy's next to map.get(n.next) and its random to map.get(n.random). This works, but the map holds an entry for every node.

Weaving gives the same lookup with no map. Each copy is inserted between its original and the original's old next, so the copy of a node n is n.next. To visit only the original nodes, a loop steps with n = n.next.next, jumping over the copy each time.

Setting the random pointers

Why not set random while weaving? Because the target's copy may not exist yet, as with 1' and 2' in the picture. So a second pass runs after every copy is in place. For each original n, its copy is n.next, and the copy of n.random is n.random.next, so the pass sets n.next.random = n.random.next.

When n.random is null there is no node to step from, and the copy's random simply stays null, as a new node starts out.

Taking the lists apart

How do we end up with two separate lists? The caller still owns the original list, so it should look the same afterwards. A third pass walks the woven list once more. For each original n and its copy, n.next skips over the copy to the next original, and the copy's next skips over that original to the next copy. The last copy gets null.

Java Solution

The method copyRandomList works in these steps:

  1. First, if head is null, the list is empty and so is its copy: return null.
  2. Weave in the copies with a loop whose variable n visits each original node. For each one, create copy with new Node(n.val), point copy.next at the node after n, then point n.next at copy. The loop steps with n = n.next.next to jump over the copy it just made.
  3. A second loop visits the originals the same way. When n.random is not null, it sets n.next.random = n.random.next.
  4. Save the copy's first node, head.next, in copyHead. A third loop takes the copy of each n, sets n.next to the node after the copy, and sets the copy's next to the node after that, or null at the end. Since n.next is already restored, this loop steps with n = n.next.
  5. Return copyHead.

The small Node class holds a value and the two pointers. Three helpers support main: build makes a list from the [value, position] pairs (with -1 for null), show prints a list in that same form, and sharesNodes reports whether the copy reaches any original node.

The main method copies Example 1 and then prints the original again, copies Example 2, copies a single node whose random is itself, and copies an empty list.

Java
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

public class CopyListWithRandomPointer {

    static class Node {
        int val;
        Node next;
        Node random;

        Node(int val) {
            this.val = val;
        }
    }

    public static Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        // 1. Put each copy right after its original: A -> A' -> B -> B' ...
        for (Node n = head; n != null; n = n.next.next) {
            Node copy = new Node(n.val);
            copy.next = n.next;
            n.next = copy;
        }
        // 2. A copy's random is the node right after the original's random.
        for (Node n = head; n != null; n = n.next.next) {
            if (n.random != null) {
                n.next.random = n.random.next;
            }
        }
        // 3. Split the two lists apart.
        Node copyHead = head.next;
        for (Node n = head; n != null; n = n.next) {
            Node copy = n.next;
            n.next = copy.next;
            copy.next = (copy.next != null) ? copy.next.next : null;
        }
        return copyHead;
    }

    // Builds a list from pairs {value, index of random node}; -1 means null.
    static Node build(int[][] pairs) {
        List<Node> nodes = new ArrayList<>();
        for (int[] p : pairs) {
            nodes.add(new Node(p[0]));
        }
        for (int i = 0; i < pairs.length; i++) {
            if (i + 1 < nodes.size()) {
                nodes.get(i).next = nodes.get(i + 1);
            }
            if (pairs[i][1] >= 0) {
                nodes.get(i).random = nodes.get(pairs[i][1]);
            }
        }
        return nodes.isEmpty() ? null : nodes.get(0);
    }

    // Prints a list as [[value, index of random node], ...].
    static String show(Node head) {
        Map<Node, Integer> index = new IdentityHashMap<>();
        int i = 0;
        for (Node n = head; n != null; n = n.next) {
            index.put(n, i++);
        }
        List<String> parts = new ArrayList<>();
        for (Node n = head; n != null; n = n.next) {
            Object r = (n.random == null) ? "null" : index.get(n.random);
            parts.add("[" + n.val + ", " + r + "]");
        }
        return parts.toString();
    }

    // True if any node of the copy, or any random it points to, is a node of the original.
    static boolean sharesNodes(Node original, Node copy) {
        Map<Node, Boolean> seen = new IdentityHashMap<>();
        for (Node n = original; n != null; n = n.next) {
            seen.put(n, true);
        }
        for (Node n = copy; n != null; n = n.next) {
            if (seen.containsKey(n) || (n.random != null && seen.containsKey(n.random))) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Node head = build(new int[][] {{7, -1}, {13, 0}, {11, 4}, {10, 2}, {1, 0}});
        Node copy = copyRandomList(head);
        System.out.println("copy:           " + show(copy));
        System.out.println("original after: " + show(head));
        System.out.println("shares nodes:   " + sharesNodes(head, copy));

        Node two = build(new int[][] {{1, 1}, {2, 1}});
        System.out.println("copy:           " + show(copyRandomList(two)));

        Node self = build(new int[][] {{5, 0}});
        Node selfCopy = copyRandomList(self);
        System.out.println("copy:           " + show(selfCopy));
        System.out.println("random is self: " + (selfCopy.random == selfCopy));

        System.out.println("empty list:     " + copyRandomList(null));
    }
}

Running it prints:

Output
copy:           [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
original after: [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
shares nodes:   false
copy:           [[1, 1], [2, 1]]
copy:           [[5, 0]]
random is self: true
empty list:     null

The copy of Example 1 prints as [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]], the same as the input. The original after line is identical too, so the third loop put every next pointer of the original back. The shares nodes line says false: neither the copy's nodes nor their random pointers lead into the original list.

Look at random is self: true. The single node 5 points at itself, and its copy points at the copy, not at the old node 5. The weaving handles this without a special case, because n.random.next is then n.next, the copy. The last line shows that an empty list gives back null.

The second loop is easy to write as n.next.random = n.random, leaving out .next. We ran that version: the copy of Example 1 then prints as [[7, null], [13, null], [11, null], [10, null], [1, null]], and shares nodes says true. Every random leads to an original node, which show cannot find in the copy, so it prints null.

Complexity

The method walks the list three times and creates one new node for each original node.

  • Time: O(n), for a list of n nodes: each of the three loops visits every original node once, and does a fixed number of pointer changes there, even though the woven list briefly has 2n nodes.
  • Space: O(1) besides the copy. The n new nodes are the answer itself. Apart from them, the method keeps only n, copy and copyHead, where the table version would need a map entry for every node.

A map from each original to its copy is also how a graph is copied in Clone Graph.