πDay 14. Clone an Undirected Graph π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a connected undirected graph represented by an adjacency list, adjList[][], with n nodes (each node having a distinct label from 0 to n-1), your task is to create a clone (deep copy) of this graph. Each node in the graph has:
An integer
valA list
neighborscontaining references to its adjacent nodes
Structure
class Node {
int val;
List<Node> neighbors;
}Return a reference to the cloned graph such that the cloned graph is identical to the original graph. The driver code will then print true if the clone is correct; otherwise it prints false.
Note: Sorry for uploading late, my Final Sem exam is going on.
π Example Walkthrough:
Example 1
Input:
n = 4 adjList = [[1, 2], [0, 2], [0, 1, 3], [2]]
Output:
true
Explanation:
The cloned graph is structurally identical to the original. Driver code checks memory and structure integrity.
Example 2
Input:
n = 3 adjList = [[1, 2], [0], [0]]
Output:
true
Explanation:
The cloned graph is identical to the original one, hence driver code outputs true.
Constraints
$( 1 \leq n \leq 10^4 )$
$( 0 \leq \text{number of edges} \leq 10^5 )$
$( 0 \leq \text{adjList[i][j]} < n )$
π― My Approach:
BFS-Based Graph Clone using Queue
Algorithm Steps:
Initialization:
If the starting node is
null, returnnull.Create a hash map (or dictionary) to store mappings from each original node to its clone.
Initialize a queue and enqueue the starting node.
BFS Traversal:
While the queue is not empty:
Dequeue the front node.
For each neighbor of the dequeued node:
If the neighbor hasn't been cloned (i.e., not present in the map), create its clone, store it in the map, and enqueue the neighbor.
Append the clone of the neighbor to the
neighborslist of the clone corresponding to the current node.
Return:
After processing all nodes, return the clone corresponding to the starting node.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N + M), whereNis the number of nodes andMis the number of edges. We visit each node and edge exactly once during the clone.Expected Auxiliary Space Complexity:
O(N), used by the hash map and the queue.
π Solution Code
Code (C++)
β‘ Alternative Approaches
π 2οΈβ£ DFS-Based Clone (Recursive)
Algorithm Steps:
Use a
map<Node*, Node*>to keep track of original β clone mappings.Recursively visit each neighbor and clone them.
Return the cloned node after recursively linking its neighbors.
π Complexity Analysis:
Time Complexity:
O(N + M)β Each node and edge visited once.Space Complexity:
O(N)β For hashmap and recursion stack.
β Why This Approach?
Very elegant and simple implementation that leverages recursion, suitable for medium-size graphs.
π 3οΈβ£ DFS-Based Clone (Iterative using Stack)
Algorithm Steps:
Use a stack to simulate DFS traversal.
Maintain a
map<Node*, Node*>for cloning references.Clone each unvisited neighbor during traversal.
Append the neighbors to the corresponding clone.
π Complexity Analysis:
Time Complexity:
O(N + M)β Visit every node and edge once.Space Complexity:
O(N)β Hashmap and stack.
β Why This Approach?
Avoids recursion and risk of stack overflow. Ideal when recursion depth is a limitation.
π Comparison of Approaches
Approach
β±οΈ Time Complexity
ποΈ Space Complexity
β Pros
β οΈ Cons
BFS (Queue + Map)
π‘ O(N + M)
π’ O(N)
Iterative, clean traversal
Slightly more space for queue
DFS (Recursive)
π‘ O(N + M)
π’ O(N)
Concise and elegant
Risk of stack overflow on deep graphs
DFS (Iterative using Stack)
π‘ O(N + M)
π’ O(N)
Avoids recursion limit
More verbose and a bit complex
β Best Choice?
Use BFS for queue-based iterative style and easier debugging.
Prefer Recursive DFS for elegance, unless you're dealing with very deep or cyclic graphs.
Choose Iterative DFS if recursion depth is a concern or restricted.
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated