Recursion

Clone Graph

Graphs

Given a node in a graph node, clone the graph, and return the cloned node.

When you modify the cloned graph, it should have no effect on the original graph. This means that you can't simply return the original node as the solution to the problem.

Clone Graph - image
Clone Graph - image
First Few Test Cases:
cloneGraph(GraphNode.of([[0]]))
# GraphNode.of([[0]])
cloneGraph(GraphNode.of([[0, 0]]))
# GraphNode.of([[0, 0]])
cloneGraph(GraphNode.of([[0, 1, 2], [1], [2]]))
# GraphNode.of([[0, 1, 2], [1], [2]])

0. Problem

We want to write a function that takes in a node, and returns its clone.

cloneGraph(node)

1. Recursion

To write the recursion, we first have to copy the current node. After we do this, we need to point the node to the clones of its neighbor nodes, like this:

Clone Graph - image

Here's the recursion:

cloneGraph(node) = (    
    # clone the current node
    clone = GraphNode(node.val)
    
    # point the clone to its cloned neighbors
    clone.neighbors = [cloneGraph(nbr) for nbr in node.neighbors] 
    return clone
)

2. Base case

We need to make sure we don't enter any infinite cycles since we're dealing with graphs. We should stop if we get to a node we've already cloned. This way we never clone the same node twice, so our code can't possibly run forever.

To do this, we'll store all the nodes we've visited in a HashMap called cloneOfNode. Here's the base case:

if node in cloneOfNode:
    return cloneOfNode[node] # return previously computed clone

3. Code

Here's the full code:

cloneOfNode = {} # node -> clone

def cloneGraph(node):
    # base case
    if node in cloneOfNode:
        return cloneOfNode[node]

    # recursion
    clone = GraphNode(node.val)
    cloneOfNode[node] = clone # mark node as cloned
    clone.neighbors = [cloneGraph(nbr) for nbr in node.neighbors]

    return clone

Time Complexity O(n)O(n). We visit every node in the graph.

Space Complexity O(n)O(n). We store every node in the HashMap cloneOfNode.

Mark as Completed:
Submits:
cloneGraph
Imports:
GraphNode
Test your code to get an output here!
cloneGraph(
)
Test your code to get an output here!