-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path133.clone-graph.py
More file actions
66 lines (49 loc) · 1.95 KB
/
Copy path133.clone-graph.py
File metadata and controls
66 lines (49 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#
# @lc app=leetcode id=133 lang=python3
#
# [133] Clone Graph
#
# @lc code=start
# c.f.: 138
# Definition for a Node.
from typing import Dict, Optional
class Node:
def __init__(self, val=0, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class Solution:
# key challenges are:
# - Handling cycles - graphs can have circular references, so we need to track visited nodes
# - Deep copying - creating new nodes rather than copying references
# - Preserving relationships - ensuring all neighbor connections are maintained
def cloneGraph(self, node: Node) -> Optional[Node]:
# or we can put it in dfs() args to save space, but less intuitive
cloned: Dict[Node, Node] = {}
# The DFS approach with a HashMap is most commonly used because:
# - It naturally handles the recursive structure of graphs
# - The HashMap prevents infinite recursion by tracking already-cloned nodes
# - It's intuitive and has optimal time/space complexity
def dfs(node: Node) -> Optional[Node]:
if not node:
return
if node in cloned:
return cloned[node]
# create clone of current node
node_clone = Node(node.val)
cloned[node] = node_clone
# filling in neighbors for each node clone
for neighbor in node.neighbors:
neighbor_clone = dfs(neighbor)
if neighbor_clone:
node_clone.neighbors.append(neighbor_clone)
return node_clone
return dfs(node)
# Complexity Analysis
# - Time Complexity: O(N + M)
# N = number of nodes
# M = number of edges
# We visit each node and edge exactly once
# - Space Complexity: O(N)
# HashMap to store N cloned nodes
# Recursion stack depth up to N (in worst case of linear graph)
# @lc code=end