codejump
MediumPythonJavaScriptTypeScript

Graph — Clone a Graph

Data StructuresGraphsDFSHash Table

Implement cloneGraph(node): return a deep copy of a connected undirected
graph given one of its nodes. Each node has a val and a list of neighbors.
The copy must be made of brand-new nodes — no node may be shared with the
original — and must preserve every edge, including cycles.

solve(adjList) is already wired. It builds the graph from an adjacency list
(adjList[i] holds the neighbours of node i + 1), calls your cloneGraph,
and returns [adjacencyListOfTheCopy, sharedNodeCount]. A correct clone gives the
same adjacency list and 0 shared nodes.

Examples

solve([[2,4],[1,3],[2,4],[1,3]])  → [[[2,4],[1,3],[2,4],[1,3]], 0]
solve([[]])                       → [[[]], 0]    // a single node, no edges
solve([])                         → [[], 0]      // empty graph

The graph can contain cycles, so you need a map from original node → its copy
to avoid cloning a node twice (and to avoid infinite recursion).

Sample tests

Test #1Square with a cycle
Input: [[[2,4],[1,3],[2,4],[1,3]]]
Output: [[[2,4],[1,3],[2,4],[1,3]],0]
Test #2Single node
Input: [[[]]]
Output: [[[]],0]
Test #3Empty graph
Input: [[]]
Output: [[],0]