Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

142. Clone Graph

MediumDay 42 of 60Graphs

You are given a reference to one node of a connected undirected graph. Each Node has an integer val and a list neighbors. Return a deep copy of the whole graph: brand new nodes with the same values and the same connections, and no reference to any original node. In the tests, the graph is written as an adjacency list where node i (1-indexed) has value i, and you receive node 1.

Example 1
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Four nodes in a square: 1 links to 2 and 4, 2 links to 1 and 3, and so on.
Example 2
Input: adjList = [[]]
Output: [[]]
One node with no neighbours.
Constraints
  • 0 <= number of nodes <= 100
  • 1 <= Node.val <= 100 and values are unique
  • No repeated edges and no self-loops
  • The graph is connected
Hints
Frequently asked at: Meta, Google, Amazon, Microsoft
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min