Clone Graph in Python and Java
In this tutorial, we will learn LeetCode #133: Clone Graph in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Clone Graph Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use depth first search because it gives a clean and optimized solution.
Example input: graph = [[2,4],[1,3],[2,4],[1,3]] Expected result: Output: cloned graph Explanation: Every node is copied with the same neighbors.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: graph = [[2,4],[1,3],[2,4],[1,3]] Approach: depth first search We update variables step by step until we reach: Output: cloned graph
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why depth first search is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. graph = [[2,4],[1,3],[2,4],[1,3]] We will solve it using depth first search. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: cloned graph Why? Every node is copied with the same neighbors.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: cloned graph
Example 1
Input: graph = [[2,4],[1,3],[2,4],[1,3]] Output: Output: cloned graph Explanation: Every node is copied with the same neighbors.
Example 2
Input: graph = [[2,3],[1,4],[1,4],[2,3]] Output: cloned graph Explanation: Every node is copied with the same neighbor connections.
Python Code
Here is the complete Python solution for LeetCode #133.
from collections import deque
class Node:
def __init__(self, val=0, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class GraphCloner:
def clone_graph(self, node):
if not node:
return None
copies = {}
def dfs(current):
if current in copies:
return copies[current]
copy = Node(current.val)
copies[current] = copy
for neighbor in current.neighbors:
copy.neighbors.append(dfs(neighbor))
return copy
return dfs(node)
def graph_values(node):
seen = set()
queue = deque([node])
values = []
while queue:
current = queue.popleft()
if current in seen:
continue
seen.add(current)
values.append(current.val)
for neighbor in current.neighbors:
queue.append(neighbor)
return values
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.neighbors = [node2, node3]
node2.neighbors = [node1]
node3.neighbors = [node1]
cloner = GraphCloner()
cloned = cloner.clone_graph(node1)
print(graph_values(cloned)) # Output: [1, 2, 3]
print(cloned is node1) # Output: FalseJava Code
Here is the complete Java solution for LeetCode #133.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
class Node {
public int val;
public List<Node> neighbors;
public Node(int val) {
this.val = val;
this.neighbors = new ArrayList<>();
}
}
class GraphCloner {
private Map<Node, Node> copies = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
if (copies.containsKey(node)) return copies.get(node);
Node copy = new Node(node.val);
copies.put(node, copy);
for (Node neighbor : node.neighbors) {
copy.neighbors.add(cloneGraph(neighbor));
}
return copy;
}
private static List<Integer> graphValues(Node node) {
List<Integer> values = new ArrayList<>();
Set<Node> seen = new HashSet<>();
Queue<Node> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()) {
Node current = queue.poll();
if (seen.contains(current)) continue;
seen.add(current);
values.add(current.val);
for (Node neighbor : current.neighbors) queue.offer(neighbor);
}
return values;
}
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.neighbors.add(node2);
node1.neighbors.add(node3);
node2.neighbors.add(node1);
node3.neighbors.add(node1);
GraphCloner cloner = new GraphCloner();
Node cloned = cloner.cloneGraph(node1);
System.out.println(graphValues(cloned)); // [1, 2, 3]
System.out.println(cloned == node1); // false
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #133: Clone Graph becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.