Copy List with Random Pointer LeetCode solution in Python

1
from collections import defaultdict
2

3
"""
4
# Definition for a Node.
5
class Node:
6
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
7
self.val = int(x)
8
self.next = next
9
self.random = random
10
"""
11

12

13
class Solution:
14
def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
15

16
# ll=res
17
# k=0
18
# ind=0
19
# kmk=1
20
jj = None
21
g = defaultdict(lambda: -1)
22
k = 0
23
hh = head
24
while head:
25
res = Node(head.val)
26
if k == 0:
27
jj = res
28

29
if k == 1:
30
prev.next = res
31

32
g[head] = res
33
prev = res
34
k = 1
35
head = head.next
36

37
# print(g)
38

39
# for i in g:
40
# print(i.val,g[i].val)
41

42
kk = jj
43
mm = jj
44
# print(head)
45
while hh:
46
if hh.random != None:
47

48
jj.random = g[hh.random]
49
else:
50
jj.random = None
51
hh = hh.next
52

53
jj = jj.next
54
# head=head.next
55
kkk = kk
56
# while(kk):
57
# print(kk.val)
58
# kk=kk.next
59

60
return kkk
61

62

63
# if g[ind]!=-1:
64
# g[ind].random=res
65

66
# res=Node(head.val)
67
# if kmk==1:
68
# ll=res
69
# kmk=0
70
# mm=head.next
71
# if mm:
72

73
# jk=Node(mm.val)
74
# res.next=jk
75
# if head.random !=None:
76
# g[head.random]=res
77
# else:
78
# res.random=None
79
# head=head.next
80
# ind+=1
81
# # res=res.next
82

83
# return ll
84

85
# if k==0:
86
# res.val=head.val
87
# mm=head.next

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0