Tutorialspoint
Problem
Solution
Submissions

Clone a Graph

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to clone an undirected graph. Each node in the graph contains a value and a list of its neighbors. Implement the CloneGraph(Node node) function that returns a deep copy (clone) of the graph.

Example 1
  • Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
  • Output: [[2,4],[1,3],[2,4],[1,3]]
  • Explanation:
    • Node 1's neighbors are nodes 2 and 4.
    • Node 2's neighbors are nodes 1 and 3.
    • Node 3's neighbors are nodes 2 and 4.
    • Node 4's neighbors are nodes 1 and 3.
Example 2
  • Input: adjList = [[]]
  • Output: [[]]
  • Explanation:
    • The graph has only one node with no neighbors.
Constraints
  • The number of nodes in the graph is in the range [0, 100]
  • 1 <= Node.val <= 100
  • Node.val is unique for each node
  • There are no repeated edges and no self-loops in the graph
  • Time Complexity: O(N + E) where N is the number of nodes and E is the number of edges
  • Space Complexity: O(N)
GraphAlgorithmsDeloitteAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash map to keep track of nodes that have already been processed
  • Apply either BFS or DFS to traverse the graph
  • For each node, create a clone and recursively clone its neighbors
  • Ensure you handle cycles in the graph correctly
  • Return null if the input node is null

Steps to solve by this approach:

 Step 1: Create a dictionary to track visited nodes and their clones
 Step 2: Handle base case: if the node is null, return null
 Step 3: If the node has already been visited, return its existing clone from the dictionary
 Step 4: Create a new node with the same value as the original node
 Step 5: Add the mapping of original node to clone in the visited dictionary
 Step 6: Recursively clone all neighbors of the node
 Step 7: Add all cloned neighbors to the cloned node's neighbor list and return it

Submitted Code :