CodingNodes / Graphs / Clone Graph System design Space play · ←→ step · R restart

Problem

You are given one node of a connected, undirected graph. Every node has an integer val and a list neighbors of the nodes it is connected to.

Build a deep copy of the graph: brand new nodes with the same values, where each node's neighbors list holds new nodes only, in the same order as in the original. Return the copy of the node you were given.

In the examples the graph is written as an adjacency list: the node with value i + 1 has the neighbours listed at position i, and the node you receive is always node 1. [] means there is no graph.

Constraints

  • 0 ≤ number of nodes ≤ 100
  • Node values are the numbers 1 to n, each used once
  • No self-loops and no repeated edges; the graph is connected

Examples: pick one to animate

Solutions

TimeO(V + E) SpaceO(V)

Time: Every node enters the queue once, and each edge is looked at twice, once from each end.

Space: The map holds one entry per node and the queue never holds more than V nodes. The copy itself is the output.

Keep a map from every original node to its copy. Start by copying the given node, then process a queue: take a node, look at each neighbour, and if the neighbour has no copy yet, make one and queue it. Either way, add the neighbour's copy to the copy of the current node. The map is also the "already visited" set, so cycles cannot make the search run forever.