Problem Summary:
A linked list is given where each node contains an additional random pointer, which could point to any node in the list or to null
. The task is to create a deep copy of this list.
Each node is defined as:
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = x
self.next = next
self.random = random
Q: Are the values of the nodes guaranteed to be unique?
A: No, node values are not necessarily unique, but the random pointers can point to any node or null
.
Q: Do we need to handle any special edge cases like an empty list? A: Yes, we need to handle the case where the input list is empty.
The strategy to solve this problem involves three main steps:
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = x
self.next = next
self.random = random
def copyRandomList(head: 'Node') -> 'Node':
if not head:
return None
# Creating a mapping from old nodes to new nodes
old_to_new = {}
# Step 1: Create a copy of each node and store it in the dictionary
current = head
while current:
old_to_new[current] = Node(current.val)
current = current.next
# Step 2: Assign the next and random pointers
current = head
while current:
if current.next:
old_to_new[current].next = old_to_new[current.next]
if current.random:
old_to_new[current].random = old_to_new[current.random]
current = current.next
# Step 3: Return the head of the new list
return old_to_new[head]
O(N)
, where N
is the number of nodes in the linked list. We iterate through the list a constant number of times.O(N)
, where N
is the number of nodes in the linked list. We use a dictionary to store the mapping of old nodes to new nodes.This completes our implementation and explanation. If there are additional questions or edge cases to consider, feel free to ask!
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?