KatInterview

133. Clone Graph

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a deep copy of a given connected undirected graph. A deep copy means we need to create a completely new set of nodes and edges that have the same values and structure as the original graph. We are given a reference to one node in the original graph.

Solution

Clone Graph in Python

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

from typing import Optional
import collections

class Solution:
    def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
        if not node:
            return None

        # Map to store the mapping from original nodes to their clones.
        # Key: original node, Value: cloned node.
        oldToNew = {}

        # Queue for BFS traversal, stores original nodes to be processed.
        queue = collections.deque([node])

        # 1. Clone the starting node and set up the initial state.
        # The neighbors list will be populated during the traversal.
        clone_node = Node(node.val)
        oldToNew[node] = clone_node
        
        # 2. Perform BFS traversal.
        while queue:
            # Get the current original node from the front of the queue.
            u = queue.popleft()

            # Iterate through the neighbors of the current original node.
            for v in u.neighbors:
                # If the neighbor has not been cloned yet.
                if v not in oldToNew:
                    # Clone the neighbor and store the mapping.
                    oldToNew[v] = Node(v.val)
                    # Add the original neighbor to the queue to process it later.
                    queue.append(v)
                
                # Add the cloned neighbor to the neighbors list of the cloned current node.
                oldToNew[u].neighbors.append(oldToNew[v])

        # Return the clone of the starting node.
        return clone_node

Clone Graph in Java

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}
*/
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

class Solution {
    public Node cloneGraph(Node node) {
        if (node == null) {
            return null;
        }

        // Map to store the mapping from original nodes to their clones.
        // Key: original node, Value: cloned node.
        Map<Node, Node> oldToNew = new HashMap<>();

        // Queue for BFS traversal, stores original nodes to be processed.
        Queue<Node> queue = new LinkedList<>();

        // 1. Clone the starting node and set up the initial state.
        Node cloneNode = new Node(node.val, new ArrayList<>());
        oldToNew.put(node, cloneNode);
        queue.add(node);

        // 2. Perform BFS traversal.
        while (!queue.isEmpty()) {
            // Get the current original node from the front of the queue.
            Node u = queue.poll();

            // Iterate through the neighbors of the current original node.
            for (Node v : u.neighbors) {
                // If the neighbor has not been cloned yet.
                if (!oldToNew.containsKey(v)) {
                    // Clone the neighbor and store the mapping.
                    oldToNew.put(v, new Node(v.val, new ArrayList<>()));
                    // Add the original neighbor to the queue to process it later.
                    queue.add(v);
                }
                // Add the cloned neighbor to the neighbors list of the cloned current node.
                oldToNew.get(u).neighbors.add(oldToNew.get(v));
            }
        }

        // Return the clone of the starting node.
        return cloneNode;
    }
}

Clone Graph in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

#include <vector>
#include <queue>
#include <unordered_map>

class Solution {
public:
    Node* cloneGraph(Node* node) {
        if (!node) {
            return nullptr;
        }

        // Map to store the mapping from original nodes to their clones.
        // Key: original node, Value: cloned node.
        std::unordered_map<Node*, Node*> oldToNew;

        // Queue for BFS traversal, stores original nodes to be processed.
        std::queue<Node*> q;

        // 1. Clone the starting node and set up the initial state.
        Node* cloneNode = new Node(node->val);
        oldToNew[node] = cloneNode;
        q.push(node);

        // 2. Perform BFS traversal.
        while (!q.empty()) {
            // Get the current original node from the front of the queue.
            Node* u = q.front();
            q.pop();

            // Iterate through the neighbors of the current original node.
            for (Node* v : u->neighbors) {
                // If the neighbor has not been cloned yet.
                if (oldToNew.find(v) == oldToNew.end()) {
                    // Clone the neighbor and store the mapping.
                    oldToNew[v] = new Node(v->val);
                    // Add the original neighbor to the queue to process it later.
                    q.push(v);
                }
                // Add the cloned neighbor to the neighbors list of the cloned current node.
                oldToNew[u]->neighbors.push_back(oldToNew[v]);
            }
        }

        // Return the clone of the starting node.
        return cloneNode;
    }
};

Clone Graph in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     neighbors: _Node[]
 * 
 *     constructor(val?: number, neighbors?: _Node[]) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.neighbors = (neighbors===undefined ? [] : neighbors)
 *     }
 * }
 * 
 */

function cloneGraph(node: _Node | null): _Node | null {
	if (!node) {
        return null;
    }

    // Map to store the mapping from original nodes to their clones.
    const oldToNew = new Map<_Node, _Node>();

    // Queue for BFS traversal, stores original nodes to be processed.
    const queue: _Node[] = [node];

    // 1. Clone the starting node and set up the initial state.
    const cloneNode = new _Node(node.val);
    oldToNew.set(node, cloneNode);
    
    // 2. Perform BFS traversal using an array as a queue.
    let head = 0;
    while (head < queue.length) {
        // Get the current original node from the front of the queue.
        const u = queue[head++];

        // Iterate through the neighbors of the current original node.
        for (const v of u.neighbors) {
            // If the neighbor has not been cloned yet.
            if (!oldToNew.has(v)) {
                // Clone the neighbor and store the mapping.
                oldToNew.set(v, new _Node(v.val));
                // Add the original neighbor to the queue to process it later.
                queue.push(v);
            }
            // Add the cloned neighbor to the neighbors list of the cloned current node.
            // The `!` asserts that the value exists in the map, which is guaranteed by our logic.
            oldToNew.get(u)!.neighbors.push(oldToNew.get(v)!);
        }
    }

    // Return the clone of the starting node.
    return cloneNode;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.