Skip to content

Clone Graph

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

You get one node of a connected, undirected graph. Each Node has an integer val and a list neighbors. Return a deep copy of the whole graph: brand-new nodes with the same values and the same connections, sharing no node objects with the original. If the input is None (null in TypeScript), return that.

The Node class is already in the starter. The tests describe a graph as an adjacency list where entry i lists the neighbours of the node whose value is i + 1, and you are handed node 1.

adjacency [[2, 4], [1, 3], [2, 4], [1, 3]]   (a square: 1-2-3-4-1)
  →  a new square with the same shape
 
adjacency [[]]  →  one new node with no neighbours
adjacency []    →  None

Constraints

  • 0 <= number of nodes <= 100
  • 1 <= Node.val <= 100 and every value is unique
  • No repeated edges and no self-loops