Deep Copy, Deep Dive – Clone That Graph!

Clone Graph – Making a Perfect Copy

Today’s problem is a classic graph challenge: deep copying a graph given the reference to one of its nodes.

At first glance, it may seem like a straightforward copy-paste job—but in a connected undirected graph, cycles and shared references make it trickier than it looks!

Let’s break it down!

Best Data Structure for Solving It

To tackle this, we use a HashMap (or Dictionary) to keep track of already cloned nodes. Why?

  • Graphs can have cycles.

  • Nodes can be shared across paths.

  • Without tracking, we’d create duplicate nodes or go into infinite recursion.

Different Approaches – Brute Force to Optimized

1. DFS Approach (Recursive)

We use Depth-First Search to traverse and clone nodes recursively.

class Solution { private Map<Node, Node> visited = new HashMap<>(); public Node cloneGraph(Node node) { if (node == null) return null; if (visited.containsKey(node)) return visited.get(node); Node cloneNode = new Node(node.val, new ArrayList<>()); visited.put(node, cloneNode); for (Node neighbor : node.neighbors) { cloneNode.neighbors.add(cloneGraph(neighbor)); } return cloneNode; } }

2. BFS Approach (Iterative)

class Solution { public Node cloneGraph(Node node) { if (node == null) return null; Map<Node, Node> visited = new HashMap<>(); Queue<Node> queue = new LinkedList<>(); queue.add(node); visited.put(node, new Node(node.val, new ArrayList<>())); while (!queue.isEmpty()) { Node current = queue.poll(); for (Node neighbor : current.neighbors) { if (!visited.containsKey(neighbor)) { visited.put(neighbor, new Node(neighbor.val, new ArrayList<>())); queue.add(neighbor); } visited.get(current).neighbors.add(visited.get(neighbor)); } } return visited.get(node); } }

⚠️ Common Mistakes & Pitfalls

  • Not tracking visited nodes: This leads to infinite recursion or duplicated nodes.

  • Returning new nodes without connecting neighbors properly.

  • Modifying original nodes instead of creating deep copies.

📊 Time & Space Complexity Analysis

  • Time Complexity: O(N + E)
    Where N is the number of nodes and E is the number of edges (we visit each node and edge once).

  • Space Complexity: O(N)
    Due to the visited map and recursion stack or queue (depending on DFS or BFS).

🌍 Real-World Applications

  • Cloning social networks (like a subgraph of friends).

  • Simulating virtual environments (like game maps or state trees).

  • Versioning and backup of complex reference-linked data structures.


I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!

                                                                                                                                         Signing off!! 

                                                                                                Master DSA One Problem at a Time :)

Comments

Popular posts from this blog

Trailing Zeros in Factorial – How Many and Why?

Divisible Drama — Who’s In, Who’s Out?

Zero Array After Queries