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 edgesedges[i] = [a, b]edges
Example 1
Output: [2,3]
Example 2
Output: [1,4]
Explanation: the loop is 1 - 2 - 3 - 4 - 1. Of its edges, [1,4] comes last.
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.
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, parentparent[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
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
- First, read the number of nodes from the input:
, because the graph has as many edges as nodes.n = edges.length - Create the array
with n + 1 entries, so node n is a valid index, and setparent for every node from 1 to n. Each node now is a group of its own. Entry 0 is never used.parent[i] = i - Loop over the edges in input order. For each edge
, calle on both ends to get their roots,find anda .b - If
equalsa , both ends are already in one group, so returnb . Otherwise, join the two groups withe .parent[a] = b - The helper
follows parent links from nodefind until it reaches a node that is its own parent, pointing each node it passes at its grandparent on the way.x
Every valid input has a cycle, so the last line, return new int[0]main
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:
[[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][1, 4][1, 5][3, 4][3, 1]
The last line has the cycle 2 - 4 - 3. Its edge [3, 4][2, 3]
Mind the size of parentnew int[n]ArrayIndexOutOfBoundsException
Complexity
The work is two findparent
- Time: O(n log n) in the worst case, because path halving without union by size keeps each of the 2n
calls at O(log n) steps on average, and in practice the links stay much shorter.find - Space: O(n), because
holds one entry per node andparent walks with a loop, not with calls that pile up.find
The same check, an edge whose ends are already in one group, decides