Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Graph Deep Copy

You are given a reference to a node in a connected, undirected graph. Each node in the graph contains an integer value and a list of references to its neighbors. Return a deep copy (clone) of the graph: a completely new set of node objects that mirrors the same structure and values, with no shared references to the original nodes.

The graph is guaranteed to be connected, so every node is reachable from the given starting node. There are no duplicate edges and no self-loops.

Example 1

Input (adjacency list, 1-indexed): [[2,4],[1,3],[2,4],[1,3]]

This describes a 4-node cycle: node 1 connects to 2 and 4, node 2 connects to 1 and 3, node 3 connects to 2 and 4, node 4 connects to 1 and 3.

Output: a new graph with the identical adjacency structure, built from entirely new node objects.

Example 2

Input: [[]] (a single node with no neighbors)

Output: a single cloned node with no neighbors.

Constraints

  • The number of nodes is in the range [0, 100].
  • Node values are unique integers in [1, 100].
  • The graph has no repeated edges and no self-loops.
  • The graph is connected, and the given node is always reachable from itself.

Share this question

← Back to Graphs practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.