Algo-Sim › Linked Lists
Copy List with Random Pointer
Medium · Linked Lists · step through it in Java, Python and C++ on your own input
Deep-copy a list whose nodes also have a random pointer: clone every node into a map, then wire next and random through it.
Problem
Each node of the list has a next pointer and a random pointer that points to any node of the list or to null. Build a deep copy: brand-new nodes whose next and random pointers mirror the original's structure, sharing no node with it.
Constraints
- 0 ≤ number of nodes ≤ 1000
- -10⁴ ≤ Node.val ≤ 10⁴
- random is null or points to a node in the same list
Edge cases to test
- Empty list
- Random pointers to null
- A node whose random points to itself
Follow-up questions
- How do you do it without a hash map?
- Interleave copies after each original (A → A′ → B → B′), set
A′.random = A.random.next, then split the lists: O(n) time, O(1) extra. - How does this generalise?
- Cloning any graph needs a map from original to copy to handle shared and cyclic references (LC 133).
Solution
Java
public Node copyRandomList(Node head) {
Map<Node, Node> copy = new HashMap<>();
for (Node curr = head; curr != null; curr = curr.next) {
copy.put(curr, new Node(curr.val));
}
for (Node curr = head; curr != null; curr = curr.next) {
copy.get(curr).next = copy.get(curr.next);
copy.get(curr).random = copy.get(curr.random);
}
return copy.get(head);
}Python
def copy_random_list(head):
copy = {None: None}
curr = head
while curr:
copy[curr] = Node(curr.val)
curr = curr.next
curr = head
while curr:
copy[curr].next = copy[curr.next]
copy[curr].random = copy[curr.random]
curr = curr.next
return copy[head]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
Node *copyRandomList(Node *head) {
unordered_map<Node *, Node *> copy = {};
for (Node *curr = head; curr != nullptr; curr = curr->next) {
copy[curr] = new Node(curr->val);
}
for (Node *curr = head; curr != nullptr; curr = curr->next) {
copy[curr]->next = copy[curr->next];
copy[curr]->random = copy[curr->random];
}
return copy[head];
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Reverse Nodes in k-Group (Hard)