Leetcode 138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer, which could point to any node in the list or null
.
Return a deep copy of the list.
The Linked List is represented by a node class with attributes:
Node.val
(from 0 to 1000)Node.next
(a pointer to the next node, or null)Node.random
(a pointer to any node in the list, or null)val
attributes guaranteed to be unique?random
pointer also point to null
?The problem can be approached by creating a new node for each original node and setting up the appropriate next
and random
pointers. We’ll split the process into three main steps:
random
pointers for the new nodes.Here’s the implementation in Java:
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;
// Step 1: Create new nodes and add them next to original nodes
Node iter = head;
while (iter != null) {
Node newNode = new Node(iter.val);
newNode.next = iter.next;
iter.next = newNode;
iter = newNode.next;
}
// Step 2: Set the random pointers of the new nodes
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Step 3: Separate the original list and the new list
iter = head;
Node newHead = head.next;
while (iter != null) {
Node newNode = iter.next;
iter.next = newNode.next;
iter = iter.next;
if (newNode.next != null) {
newNode.next = newNode.next.next;
}
}
return newHead;
}
}
The time complexity of this solution is (O(N)), where (N) is the number of nodes in the linked list. This is because we traverse the list a constant number of times (three passes).
The space complexity is (O(1)) because no additional space proportional to the input size is used; we are modifying the existing list structure.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?