Copy List with Random Pointer LeetCode solution in Python
1from collections import defaultdict23"""4# Definition for a Node.5class Node:6def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):7self.val = int(x)8self.next = next9self.random = random10"""111213class Solution:14def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":1516# ll=res17# k=018# ind=019# kmk=120jj = None21g = defaultdict(lambda: -1)22k = 023hh = head24while head:25res = Node(head.val)26if k == 0:27jj = res2829if k == 1:30prev.next = res3132g[head] = res33prev = res34k = 135head = head.next3637# print(g)3839# for i in g:40# print(i.val,g[i].val)4142kk = jj43mm = jj44# print(head)45while hh:46if hh.random != None:4748jj.random = g[hh.random]49else:50jj.random = None51hh = hh.next5253jj = jj.next54# head=head.next55kkk = kk56# while(kk):57# print(kk.val)58# kk=kk.next5960return kkk616263# if g[ind]!=-1:64# g[ind].random=res6566# res=Node(head.val)67# if kmk==1:68# ll=res69# kmk=070# mm=head.next71# if mm:7273# jk=Node(mm.val)74# res.next=jk75# if head.random !=None:76# g[head.random]=res77# else:78# res.random=None79# head=head.next80# ind+=181# # res=res.next8283# return ll8485# if k==0:86# res.val=head.val87# mm=head.next