Faaez Razeen

Copy List with Random Pointer

  • 2 min read
  • LC-Medium
  • Linked List

3 years ago

Solution

TimeSpaceExplanation
O(n)O(1)
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': # Create copies of all nodes copies = {None: None} cur = head while cur: copies[cur] = Node(cur.val) cur = cur.next # Form new list connections cur = head while cur: copies[cur].next = copies[cur.next] copies[cur].random = copies[cur.random] cur = cur.next return copies[head]

Recursive Solution

def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': refs = {None: None} def copy(node): if node not in refs: new_node = Node(node.val) refs[node] = new_node new_node.next = copy(node.next) new_node.random = copy(node.random) return refs[node] return copy(head)