26 · Graphs: BFS & DFS

#133 Clone Graph

Mediumsolve on LeetCode ↗

frequently reported atMetaGoogleAmazonBloombergMicrosoft

the problem

In plain words

Given a reference to a node in a connected undirected graph, return a deep copy. Each node has val and a list of neighbors.

in adjList = [[2,4],[1,3],[2,4],[1,3]]

out [[2,4],[1,3],[2,4],[1,3]]

A square 1-2-3-4. The copy must use brand-new nodes.

in adjList = [[]]

out [[]]

in adjList = []

out []

  • 0 ≤ number of nodes ≤ 100
  • Node values are unique, 1..100
  • No repeated edges, no self-loops; the graph is connected

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #138
      Copy List with Random Pointer
      Mediumin Linked Lists
    2. #200
      Number of Islands
      Mediumin Graphs