← Whiteboard questions

Clone Graph

Deep copy a network of linked nodes

DSA, Medium, Graphs

Which structure or algorithm, and what does it cost.

A network is made of node objects. Each node has a label and links, a list of the nodes it connects to. Links go both ways. Node(label) makes a new node with no links. Write copy_network(start). It returns a copy of every node reachable from start. The copy has the same labels and the same links in the same order, but no node of the copy may be a node of the original. If start is None, return None. The examples write the network as links[i], the labels linked to node i, and start is node 0.

Examples

Input links = [[1,2],[0,2],[0,1,3],[2]]
Output [[1, 2], [0, 2], [0, 1, 3], [2]]
Why the copy has 4 new nodes. Nodes 0, 1 and 2 form a triangle and node 3 hangs off node 2.
Input links = [[2,1],[0],[0]]
Output [[2, 1], [0], [0]]
Why node 0 lists node 2 before node 1, and the copy keeps that order.
Input links = [[]]
Output [[]]
Why one node with no links. The copy is one new node with no links.

Constraints

Your answer must contain

Target Aim for O(n + e) time and memory, where n is the number of nodes and e is the number of links.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Copying one node is easy. The hard part is a node you reach again from another neighbour. How do you know you already copied it?

Hint 2 the approach

Keep a table that maps each original node to its copy. Visit the network one node at a time and look in the table before you make a copy.

Hint 3 the key step

Walk the network once. Before you copy a neighbour, what do you check, and which node goes into the copy's links: the neighbour or its copy?

Walkthrough

Full walkthrough brute force to best

Brute force

Walk the network and keep the nodes seen so far in a plain list. Pass one copies every node. Pass two finds the copy of each link end by scanning the list. Each scan takes up to n steps and there are up to 2e link entries, so this costs O(n * e) time.

Best method

Keep a table from each original node to its copy, and a queue of nodes still to visit. Copy the start node, store it in the table and queue it. Take a node from the queue. For each neighbour, if the table has no copy of it, create one, store it and queue the neighbour. Then add the neighbour's copy to the links of this node's copy. The table stops the walk from looping on a cycle. It also makes a node reached by two paths be copied once, so both paths end at the same copy. Neighbours are read in order, so the copied links keep the original order.

Hand trace

Example 1: copy node 0 and queue it. Take 0: its neighbours 1 and 2 are new, so create copies 1 and 2, queue them, and give copy 0 the links [1, 2]. Take 1: neighbours 0 and 2 are in the table, so copy 1 gets [0, 2]. Take 2: neighbours 0 and 1 are in the table and 3 is new, so create copy 3, queue it, and copy 2 gets [0, 1, 3]. Take 3: neighbour 2 is in the table, so copy 3 gets [2]. The queue is empty and the copy is [[1, 2], [0, 2], [0, 1, 3], [2]].

Code

from collections import deque
def copy_network(start):
    if start is None:
        return None
    copies = {start: Node(start.label)}   # original node -> its copy
    todo = deque([start])
    while todo:
        node = todo.popleft()
        for other in node.links:
            if other not in copies:
                copies[other] = Node(other.label)
                todo.append(other)
            copies[node].links.append(copies[other])
    return copies[start]

Time and memory

O(n + e) time and O(n + e) memory. Each node is queued once and each link entry is read once. The table and queue hold at most n nodes, and the copy itself holds n nodes and e links.

Common mistakes

  • Making a new copy every time a node is met. A cycle then never ends, and a node reached twice is copied twice.
  • Adding the original neighbour to the copy's links instead of the neighbour's copy. The new network would still point into the old one.
  • Forgetting the empty network. When start is None, reading its label crashes.

Related problems

More Graphs problems
Clone Graph: hints, walkthrough and Python solution