MEDIUM NC#81 Blind #27 Graphs / DFS
133. Clone Graph
๐ Problem
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขRecursive stack flow
- โขCycle prevention
- โขPost-order reasoning
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply DFS reasoning pattern
๐ก Approach
- โ Use hash map to track cloned nodes
- โ Use DFS to traverse graph and create clones
- โ When encountering already cloned node, return from map
- โ Time: O(V + E), Space: O(V + E)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse hash map to track cloned nodes
- โขUse DFS to traverse graph and create clones
- โขWhen encountering already cloned node, return from map
Common Pitfalls
- โขTime: O(V + E), Space: O(V + E)
๐งช Test Cases
Test Case 1
Not run Input:
dfs(curr: GraphNode | null); Expected:
Computed from hidden reference Test Case 2
Not run Input:
dfs(neighbor); Expected:
Computed from hidden reference Test Case 3
Not run Input:
dfs(node); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output