Redundant Connection

Find the edge that creates a cycle in a tree-augmented graph — Union-Find detects the merge that closes a loop.

Medium
Time O(N * α(N)) Space O(N)
LeetCode
5 min read
union-find graph

Problem#

Given an undirected graph that was originally a tree with one extra edge added, return the extra edge. If multiple answers exist, return the one that appears last in the input.

Examples#

  • [[1,2],[1,3],[2,3]][2,3].
  • [[1,2],[2,3],[3,4],[1,4],[1,5]][1,4].

Constraints#

  • 3 <= edges.length <= 1000. Nodes are 1..n.

Hints#

Hint
Union-Find: an edge is redundant iff both endpoints are already in the same component.

Approach#

DSU with path compression and union by rank. Process edges in order; the first edge whose endpoints already share a root is the answer.

Solution#

Redundant Connection
class Solution {
vector<int> parent, rnk;
int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false;
if (rnk[a] < rnk[b]) swap(a, b);
parent[b] = a;
if (rnk[a] == rnk[b]) ++rnk[a];
return true;
}
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
parent.resize(n + 1); rnk.assign(n + 1, 0);
iota(parent.begin(), parent.end(), 0);
for (auto& e : edges) {
if (!unite(e[0], e[1])) return e;
}
return {};
}
};

Editorial#

A tree of n nodes has exactly n - 1 edges. Adding one more edge necessarily creates exactly one cycle, and Union-Find catches this when it sees two endpoints that already share a root. Processing edges in input order ensures we return the last-added one that closes the cycle.

Complexity#

  • Time: O(N * α(N)).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.