Redundant Connection

Find the one extra edge in a tree that has one edge too many, by adding the edges in order with union-find.

A graph started as a tree on the nodes 1 to n: all nodes were connected and no path led in a loop. Then one extra edge was added between two different nodes, so the graph now has n edges. They are given in the array edges, where edges[i] = [a, b] joins nodes a and b. Return an edge whose removal leaves a tree again. If several edges would do, return the one that comes last in edges.

Example 1
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Explanation: the loop is 1 - 2 - 3 - 4 - 1. Of its edges, [1,4] comes last.
Solution

The Idea

Picture five villages, numbered 1 to 5, and the roads of Example 2 between them. The road 1 - 2 links villages 1 and 2, then come 2 - 3 and 3 - 4. The road 1 - 4 makes a ring: from village 1 you can now reach village 4 directly, or the long way through 2 and 3. A path that leads back to where it started like this is called a cycle. The last road, 1 - 5, is the one road that reaches village 5. Each road is one edge of the graph.

Which roads could be closed so that every village is still reachable? Closing 1 - 5 cuts village 5 off. Closing any of the four roads on the ring works, because the rest of the ring still links its villages. So the answer is always an edge on the cycle, and the problem asks for the one that comes last in the input: 1 - 4.

A computer does not see the ring, though. It gets a list of pairs. How can it tell which edges form the cycle, and which of them comes last?

Add the edges one at a time, in input order, and keep track of which nodes can already reach each other. Call each such set of nodes a group. At the start, every node is a group of its own. Look at the picture below.

Example 2 drawn as a graph. Edges 1-2, 2-3 and 3-4, the 1st to 3rd, each join two groups. The 4th edge, 1-4, finds 1 and 4 already in one group, so it closes the cycle and is returned. The 5th edge, 1-5, is never checked.

The 1st edge, 1 - 2, joins the groups {1} and {2} into {1, 2}. The 2nd and 3rd edges each pull in one more node, and the row labelled 3 - 4 shows the group {1, 2, 3, 4}. Then comes the 4th edge, 1 - 4, and nodes 1 and 4 are already in one group. That edge adds a second way between them, so it closes the cycle. The 5th edge, 1 - 5, is never checked.

Why is that edge the last cycle edge in the input? Before it arrived, the graph had no cycle. The cycle it closes is made of this edge plus the path that already joined its two ends, and every edge on that path was added earlier. So the first edge whose ends are already in one group is the answer.

Solution Approach

Turning that idea into code means settling how to check one edge, first the slow way and then with a quicker way to record the groups, how to join two groups, and how to keep each check short.

Checking an edge the slow way

How do we know that both ends of an edge are already connected? The direct way is to walk the graph built so far, starting at one end, and see whether the walk reaches the other end. That walk can visit every node, so checking all n edges can take about n × n steps.

Recording the groups

Is there a faster way to ask "are these two in one group?" Give each group one node that stands for it, called its root. Every node keeps a link to another node of its group, its parent, and following parent links always ends at the root, which is its own parent. Two nodes are in one group exactly when they lead to the same root.

Finding the root is called find, joining two groups is called union, and this structure is known as union-find. Here the parents fit in an int array, parent, where parent[x] is the parent of node x.

Joining two groups

What happens when an edge joins two different groups? Only their roots change: the root of one group gets the root of the other as its parent. In Example 2, after the first three edges, node 1 points at 2, node 2 at 3, node 3 at 4, and 4 at itself. So the root of node 1 is 4, the root of node 4 is 4, and the 4th edge, 1 - 4, is the one to return.

Keeping the walk to the root short

That chain 1, 2, 3, 4 shows the risk: links can line up into a long path, and every find walks all of it. So while find walks up, it points each node it passes at its grandparent, the parent of its parent, which roughly halves the path for later calls. Jumping to the grandparent this way is called path halving. In Example 2, finding the root of node 1 moves node 1's link from 2 to 3.

An optional improvement, called union by size, makes the root of the smaller group point at the root of the larger one, so chains grow slowly. With it and path halving, each find takes nearly constant time on average. The code below stays short without it.

Java Solution

The method findRedundantConnection works in these steps:

  1. First, read the number of nodes from the input: n = edges.length, because the graph has as many edges as nodes.
  2. Create the array parent with n + 1 entries, so node n is a valid index, and set parent[i] = i for every node from 1 to n. Each node now is a group of its own. Entry 0 is never used.
  3. Loop over the edges in input order. For each edge e, call find on both ends to get their roots, a and b.
  4. If a equals b, both ends are already in one group, so return e. Otherwise, join the two groups with parent[a] = b.
  5. The helper find follows parent links from node x until it reaches a node that is its own parent, pointing each node it passes at its grandparent on the way.

Every valid input has a cycle, so the last line, return new int[0], is only there for the compiler. The main method runs both examples and two more inputs: one where the cycle closes in the middle of the list, and one where the cycle's first edge is also the first edge of the input.

Java
import java.util.Arrays;

public class RedundantConnection {

    public static int[] findRedundantConnection(int[][] edges) {
        int n = edges.length;                  // n nodes and n edges: one edge too many
        int[] parent = new int[n + 1];         // nodes are 1 to n, entry 0 is unused
        for (int i = 1; i <= n; i++) {
            parent[i] = i;                     // every node starts as its own group
        }
        for (int[] e : edges) {
            int a = find(parent, e[0]);
            int b = find(parent, e[1]);
            if (a == b) {
                return e;                      // already connected: this edge closes the cycle
            }
            parent[a] = b;                     // join the two groups
        }
        return new int[0];                     // not reached for valid input
    }

    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];     // point x at its grandparent
            x = parent[x];
        }
        return x;                              // the root of x's group
    }

    public static void main(String[] args) {
        int[][][] inputs = {
            {{1, 2}, {1, 3}, {2, 3}},
            {{1, 2}, {2, 3}, {3, 4}, {1, 4}, {1, 5}},
            {{2, 5}, {1, 2}, {1, 5}, {3, 4}, {3, 1}},
            {{3, 4}, {1, 2}, {2, 4}, {5, 3}, {2, 3}},
        };
        for (int[][] edges : inputs) {
            System.out.println(Arrays.deepToString(edges) + " -> "
                    + Arrays.toString(findRedundantConnection(edges)));
        }
    }
}

Running it prints:

Output
[[1, 2], [1, 3], [2, 3]] -> [2, 3]
[[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]] -> [1, 4]
[[2, 5], [1, 2], [1, 5], [3, 4], [3, 1]] -> [1, 5]
[[3, 4], [1, 2], [2, 4], [5, 3], [2, 3]] -> [2, 3]

Example 1 gives [2, 3] and Example 2 gives [1, 4], as expected. On the third line, the cycle 2 - 5 - 1 closes with the third edge, [1, 5], so the method returns before it ever looks at [3, 4] or [3, 1].

The last line has the cycle 2 - 4 - 3. Its edge [3, 4] is the very first edge of the input, yet the answer is [2, 3], the cycle edge that comes last. The first two cycle edges each joined two groups, and only the third found its ends already connected.

Mind the size of parent. Because the nodes are numbered from 1, an array of n entries has no slot for node n. With new int[n], Example 1 stops with an ArrayIndexOutOfBoundsException: "Index 3 out of bounds for length 3".

Complexity

The work is two find calls for each of the n edges, plus filling the parent array.

  • Time: O(n log n) in the worst case, because path halving without union by size keeps each of the 2n find calls at O(log n) steps on average, and in practice the links stay much shorter.
  • Space: O(n), because parent holds one entry per node and find walks with a loop, not with calls that pile up.

The same check, an edge whose ends are already in one group, decides Graph Valid Tree.