Redundant Connection (LeetCode 684): Solution and Explanation
A tree with n nodes had one extra edge added, so the undirected graph now contains exactly one cycle. Return an edge you can remove to get back a tree, choosing the one that appears last in the input if there are several.
Watch it run step by step
Try your own input and write the code →Intuition
A brute force tries removing each edge in turn, from last to first, and checks whether what remains is a tree with a DFS. That costs O(n) per check and O(n²) overall. It works within the limits but repeats nearly the same traversal over and over.
Instead, imagine rebuilding the graph edge by edge in the given order. As long as each new edge connects two nodes that are not yet connected, the structure stays a forest. The first edge whose two endpoints are already connected is the one that closes the cycle. Every edge before it was needed to make that connection, so this edge is the redundant one, and because it is the first edge that closes the cycle, it is also the last cycle edge in the input order, which is exactly the tie-breaking rule the problem asks for.
Union-find answers the question "are these two nodes already connected?" in near-constant time. Each component is a tree with a root; find returns the root, and union links two roots. When union discovers both endpoints share a root, it reports failure, and that edge is the answer. Path compression and union by size keep every operation fast.
Approach: Union-find, return the first edge that fails to merge
- Create
parandrankarrays of size n + 1, since nodes are labeled 1 to n. Each node starts as its own root with size 1. find(n)follows parent pointers to the root, pointing nodes to their grandparents along the way to flatten the tree.union(n1, n2)finds both roots. If they are the same, the nodes are already connected, so it returns false.- Otherwise it attaches the smaller tree under the larger one, updates the size, and returns true.
- Process edges in order and return the first edge for which
unionreturns false.
Step-by-step example
edges = [[1,2],[1,3],[2,3]]
- Start with
par = [0,1,2,3]and all sizes 1. - Edge [1,2]: roots 1 and 2 differ with equal size, so
par[1] = 2andrank[2] = 2. - Edge [1,3]:
find(1)returns 2 andfind(3)returns 3. Size 2 beats size 1, sopar[3] = 2andrank[2] = 3. - Edge [2,3]:
find(2)returns 2 andfind(3)returns 2. The roots match, sounionreturns false. - Return [2,3], the edge that closed the cycle 1, 2, 3.
Code: Python, Java, C++
1class Solution:
2 def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
3 par = [i for i in range(len(edges) + 1)]
4 rank = [1] * (len(edges) + 1)
5
6 def find(n):
7 p = par[n]
8 while p != par[p]:
9 par[p] = par[par[p]]
10 p = par[p]
11 return p
12
13 def union(n1, n2):
14 p1, p2 = find(n1), find(n2)
15 if p1 == p2:
16 return False
17
18 if rank[p1] > rank[p2]:
19 par[p2] = p1
20 rank[p1] += rank[p2]
21 else:
22 par[p1] = p2
23 rank[p2] += rank[p1]
24 return True
25
26 for n1, n2 in edges:
27 if not union(n1, n2):
28 return [n1, n2]1class Solution {
2 public int[] findRedundantConnection(int[][] edges) {
3 int[] par = new int[edges.length + 1];
4 for (int i = 0; i < par.length; i++) par[i] = i;
5
6 for (int[] edge : edges) {
7 if (find(edge[0], par) == find(edge[1], par)) return edge;
8 union(edge[0], edge[1], par);
9 }
10 return new int[0];
11 }
12
13 private int find(int n, int[] par) {
14 while (n != par[n]) {
15 par[n] = par[par[n]];
16 n = par[n];
17 }
18 return n;
19 }
20
21 private void union(int n1, int n2, int[] par) {
22 int p1 = find(n1, par);
23 int p2 = find(n2, par);
24 par[p1] = p2;
25 }
26}1class Solution {
2public:
3 vector<int> findRedundantConnection(vector<vector<int>>& edges) {
4 vector<int> par(edges.size() + 1);
5 iota(par.begin(), par.end(), 0);
6
7 for (auto& edge : edges) {
8 if (find(edge[0], par) == find(edge[1], par)) return edge;
9 unionNodes(edge[0], edge[1], par);
10 }
11 return {};
12 }
13
14 int find(int n, vector<int>& par) {
15 while (n != par[n]) {
16 par[n] = par[par[n]];
17 n = par[n];
18 }
19 return n;
20 }
21
22 void unionNodes(int n1, int n2, vector<int>& par) {
23 int p1 = find(n1, par);
24 int p2 = find(n2, par);
25 par[p1] = p2;
26 }
27};Time and space complexity
O(n × α(n))
There are n edges, and each one does two finds and at most one link, each costing O(α(n)) amortized with path compression and union by size. α grows so slowly that this is effectively linear.
O(n)
The par and rank arrays each store n + 1 entries.
Other approaches
DFS before each insertion (time O(n²), space O(n))
Build the graph incrementally and, before adding edge (u, v), run a DFS to see whether v is already reachable from u. If it is, that edge is the answer. Simple to reason about, but each check can scan the whole graph.
Find the cycle, then pick its last edge (time O(n), space O(n))
Build the full graph, locate the cycle with a DFS that records parents (or by repeatedly removing leaves), then return the cycle edge that appears latest in the input. It is linear but has more moving parts.
Common mistakes
- Sizing the arrays as n instead of n + 1. Nodes are labeled from 1, so node n would be out of range.
- Comparing the endpoints directly instead of their roots, which only detects an edge between a node and its immediate parent.
- Collecting every edge that fails and returning the first one found when scanning backward. Only one edge can fail, and it is found in the forward scan.
- Confusing this with the directed version of the problem, where a node can have two parents and union-find alone is not enough.
Frequently asked questions
Why does union-find find the redundant connection?
Union-find tracks which nodes are already connected. When an edge joins two nodes that are already in the same component, adding it would create a cycle, so that edge is the redundant one.
Why is the first failing edge also the last one in the input that could be removed?
All earlier edges were merged successfully, so they form a forest. The failing edge is the last edge of the cycle in input order, since the cycle only appears once it is added, which matches the required tie-breaker.
What is the time complexity of redundant connection?
With path compression and union by size it is O(n × α(n)), effectively linear. Space is O(n) for the parent and size arrays.