Skip to content
Decoder

Clone Graph

Medium

Problem

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.

Example 1

adjacency [[2, 4], [1, 3], [2, 4], [1, 3]]   (a square: 1-2-3-4-1)

Example 2

  →  a new square with the same shape

Example 3

Input
adjacency [[]]
Output
one new node with no neighbours

Example 4

Input
adjacency []
Output
None

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.