Skip to content

Commit fba2782

Browse files
committed
Sync LeetCode submission Runtime - 40 ms (49.19%), Memory - 18.7 MB (9.04%)
1 parent 33185f4 commit fba2782

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

0138-copy-list-with-random-pointer/solution.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
# Time: O(n)
44
# Space: O(n)
5+
56
"""
67
# Definition for a Node.
78
class Node:
@@ -12,23 +13,23 @@ def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
1213
"""
1314

1415
class Solution:
15-
def __init__(self) -> None:
16-
self.visited_hash = {}
16+
def __init__(self):
17+
# Dictionary which holds old nodes as keys and new nodes as its values.
18+
self.visitedHash = {}
1719

1820
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
19-
if head == None:
21+
if head is None:
2022
return None
2123

22-
if head in self.visited_hash:
23-
return self.visited_hash[head]
24+
# If we have already processed the current node, then we simply return the cloned version of it
25+
if head in self.visitedHash:
26+
return self.visitedHash[head]
2427

2528
node = Node(head.val, None, None)
26-
27-
self.visited_hash[head] = node
29+
self.visitedHash[head] = node
2830

2931
node.next = self.copyRandomList(head.next)
3032
node.random = self.copyRandomList(head.random)
3133

3234
return node
33-
3435

0 commit comments

Comments
 (0)