Clone Graph

Medium#133graph

You get one node of a connected undirected graph; each node has a value and a list of its neighbours. Return a deep copy: new nodes with the same values and the same edges, and no link of the copy may lead to an old node. Our graph: a triangle 1 – 2 – 3 with a tail 3 – 4 – 5, and we get node 1. The answer is node 1′ of a new graph of the same shape: 1′ – 2′ – 3′ with the tail 3′ – 4′ – 5′.

input
node: node 1 of a connected undirected graph, or null for an empty one. The tests write the graph as LeetCode does, its adjacency lists: the list at i holds the values of node i + 1’s neighbors. Node i has the value i.
returns
A deep copy of the graph: new nodes with the same values and the same neighbors, in the same order; return the copy of node. No node of the copy may be a node of the input.
constraints
  • 0 ≤ the number of nodes ≤ 100
  • every neighbor is a node of the graph, never the node itself, and listed once
  • the graph is undirected and connected
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * // Definition for a _Node.
 * function _Node(val, neighbors) {
 *    this.val = val === undefined ? 0 : val;
 *    this.neighbors = neighbors === undefined ? [] : neighbors;
 * };
 */

/**
 * @param {_Node} node
 * @return {_Node}
 */
function cloneGraph(node) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.