FrontendInterviews.dev

Loading problem…

320. Clone Graph

Medium•

You are implementing a sandboxed recommendation engine and need to copy a user-similarity graph before running mutations.

Each graph node has:

  • val: unique numeric identifier
  • neighbors: list of adjacent nodes
class Node {
  constructor(val, neighbors = []) {
    this.val = val;
    this.neighbors = neighbors;
  }
}

Write cloneGraph(node) to return a deep copy of the connected undirected graph rooted at node.

Requirements

1. Basic Functionality

  • Return null for empty input
  • Preserve full topology and values
  • Avoid shared references between original and clone

Example Usage

// Adjacency list: [[2,3],[1,4],[1,4],[2,3]]
// cloneGraph should return an isomorphic graph with fresh nodes
cloneGraph(node1);

Real-World Context

  • Safe simulation: Branch graph state without side effects
  • Rollback systems: Keep immutable snapshots
  • Graph tooling: Reuses BFS/DFS + map patterns from other traversal problems

Constraints

  • The number of nodes is in the range [0, 100]
  • 1 <= Node.val <= 100
  • Node values are unique for convenience in testing
Accepted3/4|Acceptance Rate75.0%