Taro Logo

Clone Graph

#3 Most AskedMedium
Topics:
Graphs

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

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Test case format:

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

Example 1:

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

Example 2:

Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.

Example 3:

Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.

Constraints:

  • The number of nodes in the graph is in the range [0, 100].
  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
  • There are no repeated edges and no self-loops in the graph.
  • The Graph is connected and all nodes can be visited starting from the given node.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of node values, and can there be multiple nodes with the same value?
  2. Can the graph be completely empty (i.e., the input reference is null), and what should be returned in that case?
  3. Can the graph contain self-loops (a node pointing to itself) or multiple edges between the same two nodes?
  4. Are all nodes guaranteed to be connected to the starting node, or could the graph be disconnected?
  5. What is the maximum number of nodes and edges we can expect in the graph?

Brute Force Solution

Approach

Imagine you are trying to make an exact copy of a complex web of connected dots and lines from scratch. The brute force approach involves blindly recreating every single connection by repeatedly exploring the entire network over and over again for every piece you need to duplicate.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first dot in the original network and create a brand new duplicate of it.
  2. Look at all the neighbors connected to this first dot in the original network.
  3. For each neighbor, check if you have already created a duplicate for it in your new network.
  4. If a duplicate does not exist yet, create a fresh duplicate dot.
  5. Connect your new duplicated dots in the exact same way the original dots are linked together.
  6. Repeat this exhaustive search process starting from every newly discovered connection to ensure no paths are missed.
  7. Continue revisiting and verifying every single pathway until every single dot and connection has been fully mapped and copied over.

Code Implementation

class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []


def clone_graph_brute_force(original_node):
    if original_node is None:
        return None

    # We use a lookup dictionary to track visited nodes and prevent infinite loops in cyclic graphs
    visited_mapping = {}

    def recursive_clone(current_node):
        if current_node in visited_mapping:
            return visited_mapping[current_node]

        duplicated_node = Node(current_node.val)
        visited_mapping[current_node] = duplicated_node

        # We iterate through all neighbors to mirror the exact topological structure of the original graph
        for neighbor_node in current_node.neighbors:
            duplicated_node.neighbors.append(recursive_clone(neighbor_node))

        return duplicated_node

    # We initiate the deep copy process from the starting node to traverse the entire connected component
    return recursive_clone(original_node)

Big(O) Analysis

Time Complexity
O(V + E) – The input size is defined by V, the total number of nodes (dots), and E, the total number of edges (connections) in the graph. The exhaustive search visits every single node exactly once and traverses every directed edge twice (once from each endpoint). We perform a constant amount of work per node to create its duplicate and per edge to link the neighbor references. This totals to V node operations plus E edge operations, which approximates to V + E and simplifies to Big O of V + E.
Space Complexity
O(N) – To analyze the auxiliary space complexity where N is the total number of nodes in the graph, we must look at the data structures required for the cloning process. Specifically, a hash map is used to keep track of visited nodes and store the mapping from original nodes to their newly duplicated counterparts, which grows linearly to store all N nodes. Additionally, the traversal algorithm, whether implemented via an explicit queue for breadth-first search or the implicit recursion stack for depth-first search, will store up to N frames or elements in the worst-case scenario. Combining the memory used by the hash map and the traversal mechanism, the total extra memory scales directly with the graph size. Therefore, the overall auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To create an exact duplicate of a connected network of nodes, we can explore the network step by step while keeping a handy registry of every new clone we make. This ensures that even if we visit the same part of the network multiple times or encounter loops, we never accidentally create duplicate copies or get stuck in an infinite cycle.

Here's how the algorithm would work step-by-step:

  1. Begin at the starting node of the original network and create an identical twin copy of it.
  2. Set up a tracking list or memory book to remember which original nodes have already been matched up with their newly created twin copies.
  3. Look at all the neighbors connected to your current original node to see where you can travel next.
  4. For every connected neighbor, check your memory book to see if you have already built its twin copy.
  5. If the neighbor's twin already exists in your memory book, simply connect the current twin to that existing twin.
  6. If the neighbor's twin does not exist yet, create a fresh twin copy, add it to your memory book, and connect the current twin to it.
  7. Travel along the connections to visit the unvisited neighbors and repeat this copying and connecting process until every node in the entire network has been successfully duplicated.

Code Implementation

def clone_graph(original_node):
    if not original_node:
        return None

    # A registry prevents infinite loops in cyclic graphs and duplicate node creations.
    visited_nodes_map = {}

    def depth_first_search(current_node):
        if current_node in visited_nodes_map:
            return visited_nodes_map[current_node]

        # Creating a twin copy immediately ensures we can reference it for graph cycles.
        cloned_node = Node(current_node.val)
        visited_nodes_map[current_node] = cloned_node

        for neighbor_node in current_node.neighbors:
            cloned_node.neighbors.append(depth_first_search(neighbor_node))

        return cloned_node

    # We initiate the recursive deep copy starting from the provided source node.
    return depth_first_search(original_node)

Big(O) Analysis

Time Complexity
O(V + E) – In this graph cloning approach, we visit every node (V) exactly once to create its clone and register it in our memory book. For each node, we also inspect all of its outgoing edges or neighbors (E) to set up the corresponding connections between the cloned nodes. Across the entire traversal, we perform a constant amount of work per node and per edge. This totals roughly V + E operations, which simplifies to the final Big O time complexity of O(V + E).
Space Complexity
O(N) – The space complexity is driven by two main components where N is the total number of nodes in the graph: the hash map used as a memory book to store mappings from original nodes to their cloned twins, and the recursion stack frames during graph traversal. In the worst-case scenario, every single node is stored in the hash map, and the depth of the recursive calls matches the number of nodes in a linear graph structure. Therefore, both the hash map and the maximum call stack depth grow linearly with the input size N, simplifying to a total auxiliary space of O(N).

Edge Cases

Null input node
How to Handle:
Check if the input node is null at the very beginning and return null immediately.
Graph with a single node and no neighbors
How to Handle:
Create a new clone of the node, store it in the visited map, and return it without entering any neighbor loops.
Graph containing cycles such as a triangle or self-loop
How to Handle:
Use a hash map to track visited original nodes and their clones to prevent infinite recursion and correctly wire back-edges.
Nodes with identical integer values throughout the graph
How to Handle:
Store references to the actual node objects, rather than their values, as keys in the visited hash map to differentiate them.
Deeply skewed or linear graphs resembling a linked list
How to Handle:
Iterative breadth-first search or memoized depth-first search should be used to avoid stack overflow issues in languages with strict recursion limits.
Disconnected components or unreachable nodes
How to Handle:
Since the problem specifies a connected undirected graph, we only need to traverse starting from the given reference node.
0/15 completed