Clone Graph

Make a full copy of a connected graph, with new nodes joined by the same links.

Given one node of a connected undirected graph, return a deep copy of the whole graph. Each node has an integer value val and a list of neighbours neighbors. The copy must be made of new nodes, with the same values and the same links between them, and no node of the original may appear in it.

The examples write a graph as adjList, an adjacency list: entry i lists the neighbours of the node with value i + 1. The given node is always the node with value 1.

Example 1
Input: adjList = [[2, 4], [1, 3], [2, 4], [1, 3]]
Output: [[2, 4], [1, 3], [2, 4], [1, 3]]
Explanation: four nodes in a square, 1 - 2 - 3 - 4 - 1.
Example 2
Input: adjList = []
Output: []
Explanation: the graph is empty, so the given node is null.
Solution

The Idea

Copying a road map by hand is a good picture of this problem. You draw a new dot for every town and a new line for every road, and the new map shows the same towns with the same roads. Nothing on the new sheet is cut out of the old one.

Example 1 is a small map of that kind. Its first entry, [2, 4], says node 1 is linked to 2 and 4. The second entry, [1, 3], says node 2 is linked to 1 and 3. The graph is undirected, which here means every link is listed from both ends: 2 is in the list of 1, and 1 is in the list of 2. Drawn out, the four nodes form a square.

We only hold node 1, though. To reach the others we follow its neighbours, then their neighbours. Suppose we copy node 1, then go to its first neighbour, 2, and copy it. Node 2 lists 1 as a neighbour, so following the links leads back to 1. Should we copy 1 again?

No. A second copy of 1 would break the square, and the walk 1, 2, 1, 2, ... would never stop. The copy of 2 has to link to the copy of 1 that already exists. So while copying, we must remember which original node got which copy. Look at the picture below.

The original square graph 1, 2, 3, 4 on the left, its copy 1', 2', 3', 4' on the right, and the copies map in the middle pairing each original node with its copy. When copying 2 reaches 1 again, the map already holds 1', so 2' links to it.

The original graph is on the left and its finished copy on the right, where 1' is the copy of 1, 2' the copy of 2, and so on. In the middle is the copies map, one row per original node with its copy. The highlighted row, 1 → 1', is what copying 2 finds when it reaches neighbour 1 again, so the highlighted link 2' - 1' goes to that same 1'.

The rest of the walk goes the same way. From 2 we go on to 3 and copy it, and from 3 to 4. All of the neighbours of 4, namely 1 and 3, are in the copies map already, so the walk turns back. Going as deep along the links as possible before turning back is called depth-first search, or DFS. Back at 1, its second neighbour, 4, is in the map too, and the copy is complete.

Solution Approach

Turning that idea into code means settling three things: how to copy one node and reach the rest, how to avoid copying a node twice, and when to write a new copy into the copies map. A version with a queue of nodes to visit comes as an option at the end.

Copying one node and its neighbours

What does copying a single node involve? Make a new node with the same val. Then, for each neighbour in the original's list, get that neighbour's copy and add it to the new node's list. Getting a neighbour's copy is the same job again, one node further, so the method calls itself for each neighbour. So copying node 1 starts a second call that copies node 2, while the copy of 1 is still unfinished. Because the method hands each neighbour to a call of itself, it is called recursive.

Copying each node only once

What stops the walk on the square from running forever? Without memory, the copy of 1 asks for a copy of 2, which asks for a copy of 1, and so on. The copies map stops it, and it also keeps the square from getting a second copy of 1. The method looks the node up first, and if a copy is there, returns that copy and goes no deeper.

The map is a HashMap from original node to copy. The node class, Node, keeps Java's default equals, so the map tells nodes apart by object, not by value. Two different nodes with the same val still get two copies.

When to record a new copy

Does the order inside the method matter? It does. The new node must go into the copies map as soon as it is made, before the loop over its neighbours. On the square, copying 1 leads to 2, and 2 leads back to 1 while 1 is still busy with its list. If 1 → 1' were written only after that list, 2 would not find it.

Optional: a queue instead of recursion

Each recursive call stays open until its neighbours are copied. Java keeps the open calls on its call stack, an area of memory with a fixed size, so a graph shaped like one long line makes the stack as deep as the line is long. The same copy can be made with a queue of nodes still to visit and a loop. That order, which copies all neighbours of a node before moving further away, is called breadth-first search, or BFS. It uses the same copies map.

Java Solution

The method cloneGraph works in these steps:

  1. First, create the copies map, an empty HashMap named copies, and pass it with the given node to the recursive helper copy. A new map for every call to cloneGraph means a second graph is never mixed with the first.
  2. In copy, return null when the node is null, which is the empty graph of Example 2.
  3. Look the node up in copies. If the lookup finds a copy, named done, return it.
  4. Otherwise create clone, a new node with the same val, and put the pair node → clone into copies straight away.
  5. Loop over the original's neighbours. For each neighbour, named next, call copy and add the node it returns to the neighbour list of clone. Then return clone.

Around the method sit a small Node class and three helpers for main. build makes a graph from an adjacency list, allNodes collects every node reachable from one node, and toAdjList writes a graph back as an adjacency list. The main method copies both examples, a single node with no neighbours, two linked nodes and a triangle. For each copy it also prints how many node objects the copy shares with the original.

Java
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CloneGraph {

    static class Node {
        int val;
        List<Node> neighbors = new ArrayList<>();
        Node(int val) { this.val = val; }
    }

    public static Node cloneGraph(Node node) {
        return copy(node, new HashMap<>());
    }

    private static Node copy(Node node, Map<Node, Node> copies) {
        if (node == null) {
            return null;                        // empty graph
        }
        Node done = copies.get(node);
        if (done != null) {
            return done;                        // copied already: reuse that copy
        }
        Node clone = new Node(node.val);
        copies.put(node, clone);                // record it before visiting neighbours
        for (Node next : node.neighbors) {
            clone.neighbors.add(copy(next, copies));
        }
        return clone;
    }

    // Builds the graph from its adjacency list; entry i lists the neighbours of node i + 1.
    static Node build(int[][] adjList) {
        if (adjList.length == 0) {
            return null;
        }
        Node[] nodes = new Node[adjList.length];
        for (int i = 0; i < nodes.length; i++) {
            nodes[i] = new Node(i + 1);
        }
        for (int i = 0; i < nodes.length; i++) {
            for (int v : adjList[i]) {
                nodes[i].neighbors.add(nodes[v - 1]);
            }
        }
        return nodes[0];
    }

    // Collects every node reachable from start, each object once.
    static Set<Node> allNodes(Node start) {
        Set<Node> seen = Collections.newSetFromMap(new IdentityHashMap<>());
        Deque<Node> todo = new ArrayDeque<>();
        if (start != null) {
            todo.add(start);
        }
        while (!todo.isEmpty()) {
            Node n = todo.poll();
            if (seen.add(n)) {
                todo.addAll(n.neighbors);
            }
        }
        return seen;
    }

    // Writes the graph back as an adjacency list, ordered by node value.
    static String toAdjList(Node start) {
        List<Node> nodes = new ArrayList<>(allNodes(start));
        nodes.sort((a, b) -> Integer.compare(a.val, b.val));
        List<List<Integer>> rows = new ArrayList<>();
        for (Node n : nodes) {
            List<Integer> row = new ArrayList<>();
            for (Node m : n.neighbors) {
                row.add(m.val);
            }
            rows.add(row);
        }
        return rows.toString();
    }

    static void run(int[][] adjList) {
        Node original = build(adjList);
        Node clone = cloneGraph(original);
        Set<Node> shared = allNodes(original);
        shared.retainAll(allNodes(clone));
        System.out.println(toAdjList(clone) + "   shared with the original: " + shared.size());
    }

    public static void main(String[] args) {
        run(new int[][] {{2, 4}, {1, 3}, {2, 4}, {1, 3}});
        run(new int[][] {});
        run(new int[][] {{}});
        run(new int[][] {{2}, {1}});
        run(new int[][] {{2, 3}, {1, 3}, {1, 2}});
    }
}

Running it prints:

Output
[[2, 4], [1, 3], [2, 4], [1, 3]]   shared with the original: 0
[]   shared with the original: 0
[[]]   shared with the original: 0
[[2], [1]]   shared with the original: 0
[[2, 3], [1, 3], [1, 2]]   shared with the original: 0

Look at the first line: the copy of the square reads [[2, 4], [1, 3], [2, 4], [1, 3]], exactly the input of Example 1, and it shares 0 nodes with the original. So every node in it is new, which is what makes it a deep copy. The second line, [], is the empty graph of Example 2.

The line [[]] is a single node with an empty neighbour list, copied without entering the loop at all. In the last line, the triangle 1 - 2 - 3 has a cycle of three nodes instead of four, and its copy keeps all three links.

The placement of copies.put(node, clone) matters. A test version that puts it after the neighbour loop never finds 1 in the map while 1's own list is still being copied. On the square of Example 1, that version ends with a StackOverflowError.

Complexity

Here V is the number of nodes and E the number of links, and the copies map keeps the work to one visit per node.

  • Time: O(V + E), because each of the V nodes is copied once and its neighbour list read once, and each link appears in two lists, so the loops take 2E steps in total.
  • Space: O(V) besides the copy, because the copies map holds one pair per node, and the recursion can be V calls deep on a graph shaped like one long line.

The same map from original to copy also solves Copy List with Random Pointer.