#138
Copy List with Random Pointer
medium· Linked Listruns: 0A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes whose value and connections mirror the original.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 497
class Solution:
def copyRandomList(self, head: "Node | None") -> "Node | None":
if not head:
return None
old_to_new = {}
curr = head
while curr:
old_to_new[curr] = Node(curr.val)
curr = curr.next
curr = head
while curr:
old_to_new[curr].next = old_to_new.get(curr.next)
old_to_new[curr].random = old_to_new.get(curr.random)
curr = curr.next
return old_to_new[head]
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.