Clone Graph

Medium Graph traversal Hash map DFS

Problem

Return a deep copy of a connected undirected graph. Each node has an integer value and a list of neighbours. Node values are unique.

Original: LeetCode 133: Clone Graph.

Examples

Example 1

Input`adjList = [[2, 4], [1, 3], [2, 4], [1, 3]]`
Output`[[2, 4], [1, 3], [2, 4], [1, 3]]`

Same shape, but every node in the answer is a new object.

Example 2

Input`adjList = []`
Output`[]`

A null input returns null.

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.
  • The Graph is connected and all nodes can be visited starting from the given node.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 133: Clone Graphleetcode.com