next pointer and a random pointer that can point to any node in the list or null.
Problem
Given the head of a linked list where each node contains anext pointer and a random pointer, create and return a deep copy of the linked list.
The
random pointer of a node can point to any node in the list or null. The copied list must contain completely new nodes, while preserving the same next and random relationships.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output
[[7,null],[13,0],[11,4],[10,2],[1,0]]
The output has the same values and pointer relationships as the original list, but every node is a newly created node.
Solution
This solution uses a HashMap to maintain a mapping between each original node and its corresponding copied node.First, we traverse the original list and create a new node for every original node. We store the mapping from the original node to the copied node in the HashMap.
In the second traversal, we set the
next and random pointers of every copied node. For an original node, its copied node can be retrieved from the map, and the copied versions of its next and random nodes can also be retrieved from the same map.
The HashMap is important because a random pointer can point to any node in the list. The map allows us to find the corresponding copied node in
O(1) average time.
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Map<Node, Node> map = new HashMap<>();
Node current = head;
// Create a copy of every node.
while (current != null) {
map.put(current, new Node(current.val));
current = current.next;
}
current = head;
// Set next and random pointers.
while (current != null) {
Node copy = map.get(current);
copy.next = map.get(current.next);
copy.random = map.get(current.random);
current = current.next;
}
return map.get(head);
}
}
Complexity
We traverse the linked list twice, so the time complexity isO(n), where n is the number of nodes in the list.
The HashMap stores a mapping for every original node, so the extra space complexity is
O(n).
Comments
No comments yet. Ask a question or share what helped.