Python coding

Deep copy of a graph

Each node of an undirected, connected graph has a val and a list neighbors. Write copy_graph(node): given one node, return its counterpart in a deep copy of the whole graph, made of new nodes with the same values, where each copy's neighbors lists the copies of the original's neighbors, in the same order. Values can repeat and the graph can have cycles; no node is its own neighbor. Leave the original as it was. If node is None, return None.

The tests call the provided run_copy(values, adj): node i has value values[i] and neighbors adj[i] (indexes), and your function gets node 0. It checks your copy and returns it in the same form.

  • run_copy([1,2,3,4], [[1,3],[0,2],[1,3],[0,2]]) → [[1,2,3,4],[[1,3],[0,2],[1,3],[0,2]]]
  • run_copy([5], [[]]) → [[5],[[]]]
  • run_copy([], []) → [[],[]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Traverse the original with BFS or DFS, and keep a dictionary from each original node to its copy. The dictionary is also your visited set: cycles stop there.

Hint 2

The first time you meet a node, create its copy and queue the original. Every time you cross an edge, append the copy of that neighbor, new or old.

Hint 3

Key the dictionary by the node itself, not by val: values repeat, and two different nodes with the same value need two different copies.

Solution and why it works
pythonO(V + E) · O(V) besides the copy
# --- your code ---
from collections import deque


def copy_graph(node: "Node | None") -> "Node | None":
    if node is None:
        return None
    copies = {node: Node(node.val)}          # original -> its copy; also the visited set
    queue = deque([node])
    while queue:
        cur = queue.popleft()
        for nb in cur.neighbors:
            if nb not in copies:             # first sighting: copy it now, explore it later
                copies[nb] = Node(nb.val)
                queue.append(nb)
            copies[cur].neighbors.append(copies[nb])
    return copies[node]


# --- provided: do not edit ---
class Node:
    def __init__(self, val=0, neighbors=None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []


def run_copy(values: list[int], adj: list[list[int]]) -> list[list]:
    nodes = [Node(v) for v in values]
    for node, nbrs in zip(nodes, adj):
        node.neighbors = [nodes[j] for j in nbrs]
    before = [(n.val, list(n.neighbors)) for n in nodes]
    start = copy_graph(nodes[0] if nodes else None)
    for n, (v, nbrs) in zip(nodes, before):
        if n.val != v or len(n.neighbors) != len(nbrs) or any(a is not b for a, b in zip(n.neighbors, nbrs)):
            raise ValueError("the original graph was changed: leave it as it was")
    if start is None:
        if nodes:
            raise ValueError("returned None for a non-empty graph")
        return [[], []]
    originals = {id(n) for n in nodes}
    index, seen = {id(start): 0}, [start]    # copy node -> index of the original it stands for
    for node in seen:                        # walk the copy and the original side by side
        i = index[id(node)]
        if id(node) in originals:
            raise ValueError("the copy reuses original nodes: create new ones")
        if node.val != values[i] or len(node.neighbors) != len(adj[i]):
            raise ValueError(f"the copy of node {i} has the wrong value or number of neighbors")
        for nb, j in zip(node.neighbors, adj[i]):
            if id(nb) not in index:
                index[id(nb)] = j
                seen.append(nb)
            elif index[id(nb)] != j:
                raise ValueError(f"the copy of node {i} links to the wrong node")
    if len(seen) != len(nodes):
        raise ValueError("some original node was copied more than once: reuse its first copy")
    copy_of = {index[id(n)]: n for n in seen}
    return [[copy_of[i].val for i in range(len(nodes))],
            [[index[id(nb)] for nb in copy_of[i].neighbors] for i in range(len(nodes))]]

A traversal visits every node once, and the map from original to copy does two jobs: it is the visited set that stops cycles, and it lets every edge point at the one copy of its neighbor, even one made earlier. Each node is copied once and each edge crossed once: O(V + E). Traps: copying a neighbor again on every visit (a cycle never ends, or duplicates appear), keying the map by value when values repeat, and reusing the original's neighbor list.