The 30 second answer
Each node has a next pointer and a random pointer that may point at any node or at null. I first walk the list and put a copy of every node in a map from original to clone. In a second walk I set each copy's next and random from the map, so the references go to the cloned nodes rather than the originals.
Problem A linked list node has a next pointer and a random pointer, which may point at any node in the list or at null. Return a deep copy of the list. Original: LeetCode 138: Copy List with Random Pointer.
Understanding the prompt A shallow copy would share nodes with the input. Deep copy means new nodes, with next and random pointing inside the new list. random may be null, and the list itself may be empty. The graph can have a diamond shape, so you must not clone the same original node twice.
Pattern recognition A hash map from original node to clone, which is the general graph-clone technique; Clone Graph uses the same idea.
Brute force The map-based two-pass walk below is already the standard first solution. The interesting alternative is the weave method that uses no map.
Optimal First pass: for each original node, map.put(node, new Node(node.val)). Second pass: for each original p, the clone's next is map.get(p.next) and its random is map.get(p.random). HashMap.get(null) returns null, so a null random is handled. Return map.get(head).
Alternatives Weave a copy after each original, set random as original.random.next, then split the two lists apart. That is O(1) extra space and is a strong follow-up, but it is easier to get wrong than the map.
Java solution
import java.util.HashMap;
public class CopyListWithRandomPointer {
static class Node {
int val;
Node next, random;
Node(int val) { this.val = val; }
}
static Node copyRandomList(Node head) {
var map = new HashMap<Node, Node>();
for (Node p = head; p != null; p = p.next) map.put(p, new Node(p.val));
for (Node p = head; p != null; p = p.next) {
var q = map.get(p);
q.next = map.get(p.next);
q.random = map.get(p.random);
}
return map.get(head);
}
static String show(Node head) {
var idx = new HashMap<Node, Integer>();
int i = 0;
for (Node p = head; p != null; p = p.next) idx.put(p, i++);
var sb = new StringBuilder("[");
for (Node p = head; p != null; p = p.next) {
if (sb.length() > 1) sb.append(", ");
sb.append("[").append(p.val).append(", ");
sb.append(p.random == null ? "null" : idx.get(p.random)).append("]");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
var n = new Node[] {new Node(7), new Node(13), new Node(11), new Node(10), new Node(1)};
for (int i = 0; i < n.length - 1; i++) n[i].next = n[i + 1];
n[1].random = n[0];
n[2].random = n[4];
n[3].random = n[2];
n[4].random = n[0];
System.out.println(show(copyRandomList(n[0]))); // [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
System.out.println(copyRandomList(null) == null); // true
}
}Complexity O(n) time, O(n) extra space for the map and the new nodes.
Edge cases
- Official sample [[7,null],[13,0],[11,4],[10,2],[1,0]] copies to an equal structure of new nodes.
- An empty list returns null.
- A single node whose random points at itself.
Follow-ups
- The weave method, if the interviewer forbids a map.
- Clone Graph is the same map, with a neighbour list instead of next and random.
Tests The official seven-thirteen-eleven-ten-one example copies to [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]. null copies to null.
How to say it in the interview "I clone every node into a map from original to copy, then I walk again and set each copy next and random from the map. That way random pointers land on the cloned nodes. Linear time, linear extra space. If I cannot use a map I would weave the copies into the original list, fix random, then split."
Sources (2)
- LeetCode 138: Copy List with Random Pointerleetcode.com
- Java SE 17 API: HashMapdocs.oracle.com