Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get edges, a list of n undirected edges on nodes labelled 1 to n. The graph started as a tree (connected, no cycles) and then one extra edge was added. Return an edge you can remove so the graph is a tree again. If several edges would work, return the one that appears last in edges. n is at most 1000.
Example: edges = [[1,2],[1,3],[2,3]] → [2,3]. The three edges form a triangle. Removing any one of them leaves a tree, and [2,3] comes last.
Start with brute force
Try removing each edge, from last to first. After removing it, check whether what's left is a tree: run a DFS from node 1 and see if it reaches all n nodes using the remaining n − 1 edges. The first edge that passes is your answer.
That's correct, but each check is O(n), and you might do n of them: O(n²). For n = 1000 it's fine, but it's the wrong idea. It throws away everything it learned between checks.
Building the intuition
Think about building the graph one edge at a time, starting from n isolated nodes.
Each edge either joins two separate pieces into one, or it connects two nodes that can already reach each other. The second kind is the only way to make a loop: you already had a path from a to b, and now there's a second one.
A tree has n − 1 edges, so n − 1 of our edges are joining edges. Exactly one edge is the loop-closer.
So the question is: when I look at edge (a, b), are a and b already connected? Rerunning a DFS every time costs O(n) per edge. Union-Find answers it in practically O(1): union(a, b) returns false when a and b already share a root.
What about "return the last one"? The cycle is made of several edges, and any of them could be removed. We add edges in input order, and the cycle can't be complete until all of its edges are in. So the edge that completes it, the one where union first fails, is the cycle edge that appears last in the input. That's exactly what the problem asks for.
The optimal approach
- Build a DSU with
n + 1slots (nodes are labelled from 1, so slot 0 just sits unused). - For each edge
(a, b)in order:- if
union(a, b)returnsfalse, return[a, b].
- if
- The input guarantees one extra edge, so step 2 always returns.
The subtle detail is the order. You don't need to find the whole cycle and then pick its latest edge. Processing in input order and returning the first failure gives you that edge for free.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class DSU:
def __init__(self, n: int):
self.parent = list(range(n)) # every node starts as its own root
self.size = [1] * n
def find(self, x: int) -> int:
root = x
while self.parent[root] != root:
root = self.parent[root]
# path compression: point every node we walked past straight at the root
while x != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same group
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra # union by size: hang the smaller tree under the bigger
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
dsu = DSU(len(edges) + 1) # nodes are labelled 1..n, and n == len(edges)
for a, b in edges:
if not dsu.union(a, b):
# a and b were already connected, so this edge closes the cycle.
# It's the last cycle edge in input order, which is what's asked.
return [a, b]
return [] # the input always has exactly one extra edge, so we never get hereclass DSU {
public:
vector<int> parent, sz;
DSU(int n) : parent(n), sz(n, 1) {
iota(parent.begin(), parent.end(), 0); // every node starts as its own root
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
// "union" is a C++ keyword, so this one is called unite
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (sz[ra] < sz[rb]) swap(ra, rb); // union by size: smaller tree under the bigger
parent[rb] = ra;
sz[ra] += sz[rb];
return true;
}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
DSU dsu(edges.size() + 1); // nodes are labelled 1..n, and n == edges.size()
for (auto& e : edges) {
if (!dsu.unite(e[0], e[1])) {
// already connected: this edge closes the cycle, and it's the
// last cycle edge in input order
return {e[0], e[1]};
}
}
return {}; // exactly one extra edge is guaranteed, never reached
}
};class DSU {
int[] parent, size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every node starts as its own root
size[i] = 1;
}
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (size[ra] < size[rb]) { // union by size: smaller tree under the bigger
int t = ra; ra = rb; rb = t;
}
parent[rb] = ra;
size[ra] += size[rb];
return true;
}
}
class Solution {
public int[] findRedundantConnection(int[][] edges) {
DSU dsu = new DSU(edges.length + 1); // nodes are labelled 1..n, and n == edges.length
for (int[] e : edges) {
if (!dsu.union(e[0], e[1])) {
// already connected: this edge closes the cycle, and it's the
// last cycle edge in input order
return new int[] { e[0], e[1] };
}
}
return new int[0]; // exactly one extra edge is guaranteed, never reached
}
}class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // every node starts as its own root
this.size = new Array(n).fill(1);
}
find(x) {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
// path compression: point every node we walked past straight at the root
while (x !== root) {
const nxt = this.parent[x];
this.parent[x] = root;
x = nxt;
}
return root;
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra]; // union by size
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
return true;
}
}
/**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantConnection = function (edges) {
const dsu = new DSU(edges.length + 1); // nodes are labelled 1..n, and n == edges.length
for (const [a, b] of edges) {
if (!dsu.union(a, b)) {
// already connected: this edge closes the cycle, and it's the
// last cycle edge in input order
return [a, b];
}
}
return []; // exactly one extra edge is guaranteed, never reached
};Dry run
edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
| Edge | find(a) | find(b) | Same root? | Action |
|---|---|---|---|---|
| [1, 2] | 1 | 2 | no | merge, 2 goes under 1 |
| [2, 3] | 1 | 3 | no | merge, 3 goes under 1 |
| [3, 4] | 1 | 4 | no | merge, 4 goes under 1 |
| [1, 4] | 1 | 1 | yes | return [1, 4] |
The cycle is 1–2–3–4–1. Its edges appear at positions 0 to 3, and [1, 4] is the last of them. We never even look at [1, 5].
Complexity
- Time: O(n · α(n)). At most
nunions, each effectively constant thanks to path compression and union by size. - Space: O(n) for the DSU arrays.
Edge cases and traps
- Off-by-one on labels. Nodes go from 1 to
n, so the DSU needsn + 1slots. Allocatingncrashes on noden. - Searching for the "last" edge separately. Students find the cycle with DFS, then scan for the latest cycle edge. That works, but it's extra code. The first failing union already is that edge.
- Returning
[b, a]. Return the edge exactly as it appears in the input. - Treating the graph as directed. This problem is undirected. The directed version (Redundant Connection II) is much harder, because a node can also end up with two parents.
Say it in the interview
"A tree plus one edge has exactly one cycle, and an edge closes a cycle exactly when its endpoints are already connected. So I add edges in order with Union-Find. The first edge where both ends already share a root is the loop-closer. Since the cycle can't finish until its last edge arrives, that's also the cycle edge that appears last in the input, which is what they want. O(n · α(n)) time, O(n) space."
Follow-ups interviewers ask
- "Can you do it with DFS?" Yes. Before adding each edge, DFS to check whether
aalready reachesb. That's O(n²), and it shows why Union-Find exists. - "What if the graph is directed?" That's Redundant Connection II. Handle the case where a node has two parents separately from the plain-cycle case. Union-Find still does the cycle check.
- "What if there could be several extra edges?" Every failed union is an extra edge. Collect them all, and the graph minus those edges is a spanning forest.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free