Home Leetcode

Clone Graph

Given a reference of a node in a connected undirected graph.

Constraints:

To create a clone, we must make sure a few things are correct.

Therefore BFS seems to be the correct approach, as it will reach all nodes from the root, and will traverse using the edges.

def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
	if node is None:
		return None
	
	clones = {node: Node(node.val)}
	queue = [node]
	while queue:
		curr_node = queue.pop(0)
		for neighbour in curr_node.neighbors:
			if neighbour not in clones:
				clones[neighbour] = Node(neighbour.val)
				queue.append(neighbour)
			
			clones[curr_node].neighbors.append(clones[neighbour])
	
	return clones[node]

Time Complexity

We are only doing BFS here - so the algorithm takes O(V+E)\mathcal{O}(V+ E) time.

Space Complexity

Since the output result isn’t considered as part of the space complexity analysis and no other variables are used, space is constant.