Copy List With Random Pointer: the idea to remember.
Deep copy a linked list whose nodes have both next and random pointers.
The core insight
Create one copy per original node, then wire next and random through the original to copy map.
Why it works
Every original has exactly one corresponding copy before any reference is assigned, preserving arbitrary pointer sharing.
The mistake to avoid
Copy identity, not just node values; random may be null, point backward, or point to the node itself.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Create one copy per original node, then wire next and random through the original to copy map.
public Node copyRandomList(Node head) {
Node cur = head;
HashMap<Node, Node> map = new HashMap<>();
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.