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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit