Skip to content

Commit 3689422

Browse files
committed
solve: cloneGraph
1 parent 0bf06ac commit 3689422

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

clone-graph/yolophg.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Time Complexity: O(N + E) - visit each node once and for each node, we iterate through its neighbors O(E).
2+
# Space Complexity: O(N) - store a copy of each node in the hashmap O(N).
3+
4+
class Solution:
5+
def cloneGraph(self, node):
6+
if node is None:
7+
return None
8+
9+
# dictionary to keep track of cloned nodes (original -> clone)
10+
mp = {}
11+
12+
def clone(node):
13+
if node in mp:
14+
# if the node has already been cloned, return the copy
15+
return mp[node]
16+
17+
# create a new node with the same value
18+
cpy = Node(node.val)
19+
# store it in the map so don't clone it again
20+
mp[node] = cpy
21+
22+
# clone all neighbors and add them to the new node's neighbors list
23+
for n in node.neighbors:
24+
cpy.neighbors.append(clone(n))
25+
26+
return cpy
27+
28+
return clone(node)

0 commit comments

Comments
 (0)