This practice workspace is built for desktop. Open it on a larger screen to start solving.
Clone Graph
Given a reference to a node in a connected, undirected graph, return a deep copy of the graph. Each node contains a value (int) and a list of its neighbors (List[Node]).
Input/output convention for this exercise. The graph is supplied as a 1-indexed adjacency list — adjList[i] lists the 1-indexed labels of the i+1-th node's neighbors. For example, [[2,4],[1,3],[2,4],[1,3]] describes a 4-node graph where node 1's neighbors are nodes 2 and 4, etc.
To verify that you actually deep-copied the graph (rather than returning the original references), your function must:
- Build the graph from the adjacency list (the starter provides
buildGraphandNode). - Clone it.
- Re-serialize the clone via the provided
serializeGraphhelper, which returns the adjacency list of whatever graph it walks. Return that.
The result should equal the input adjacency list when the clone is correct. The graph is guaranteed connected (LeetCode 133), so disconnected inputs are out of scope.
Empty input [] represents the empty graph; return [].
Examples
Constraints
- The number of nodes is in the range [0, 100].
- 1 <= Node.val <= 100
- Node.val is unique for each node.
- The graph is connected and all nodes can be visited starting from the given node.
Preview Mode
This is a read-only preview of DSAMind's AI coaching. Sign up to get custom feedback on your own solution.
Your approach
- Pattern:Depth-First Search
- Time:O(N)
- Space:O(1)
Complete approach — pattern and complexity both named.
Coach
What you got right
You correctly matched the sorted input requirement and implemented a linear-time scan using two pointers.
Where it diverged
No divergence detected. The code correctly aligns with the stated approach.
Next attempt: focus on
Try solving related sliding window problems to build familiarity with two-pointer variants.
Signals
No signals fired — clean run, you stayed in flow.