Redundant Connection solution explained
Redundant Connection gives you a tree with one extra edge and asks which edge to delete so a tree remains, choosing the one listed last if several work. Process the edges in order with union-find and return the first edge whose two endpoints already share a root: it closes the only loop, and it is the latest loop edge in the list. That runs in near-linear time.
By Evin JohnPublished 9 min read
The problem, in plain terms
A company's offices, labeled 1 to n, were once linked by n - 1 private lines that formed a tree: every office could reach every other in exactly one way. Then someone added one more line between two offices that were not directly linked. You get the full list of n lines in the order they appear in the records. Return one line that can be removed so the network is a tree again. If several lines would work, return the one that appears latest in the list.
Network A: [[4, 6], [1, 4], [2, 4], [2, 5], [5, 6], [6, 3]]
loop: 4-2-5-6-4 answer: [5, 6]
Network B: [[4, 2], [1, 4], [1, 2], [2, 3]]
loop: 1-4-2-1 answer: [1, 2]In network A, removing any of the four loop lines leaves a tree, so the tie-break picks [5, 6], the latest of them. Line [6, 3] comes later still, but removing it would strand office 3 and leave the loop in place. Network B makes the same point: the last line in the list, [2, 3], is not on the loop, so the answer is [1, 2]. A solution that simply returns the final edge fails both.
Confirm the assumptions out loud: the graph is connected, the extra line joins two different offices, and it does not duplicate a line already present. Under those rules there is exactly one loop.
What the interviewer is checking
This problem is popular because the efficient answer is short but the reasoning behind it is not. Anyone can say union-find; the interviewer wants to hear why the first edge it rejects is the right one given the tie-break. It also checks whether you can spot that the answer must lie on the loop, which is the observation that makes every approach work.
Brute force: try removing edges from the end
Walk the list from the last edge to the first. For each candidate, rebuild the graph without it and check whether the remaining n - 1 edges connect all n offices. With n - 1 edges, connected means tree, so the first candidate that passes is the answer, and scanning from the end honors the tie-break automatically.
def find_redundant_slow(edges):
n = len(edges)
for skip in range(n - 1, -1, -1):
nbrs = {v: [] for v in range(1, n + 1)}
for i, (a, b) in enumerate(edges):
if i != skip:
nbrs[a].append(b)
nbrs[b].append(a)
seen, stack = {1}, [1]
while stack:
for w in nbrs[stack.pop()]:
if w not in seen:
seen.add(w)
stack.append(w)
if len(seen) == n:
return edges[skip]
return []Each trial is a linear search, and there can be n trials, so this is O(n²). It is a perfectly good test oracle, and saying it first gives you a correct baseline before you optimize.
Optimal approach: union-find in input order
Add the edges one by one to a union-find structure. For each edge, look up the roots of its endpoints. Different roots mean the edge links two separate groups, so merge them. The same root means the endpoints are already connected through earlier edges, so this edge closes a loop. Return it immediately.
def find_redundant(edges):
n = len(edges)
up = list(range(n + 1)) # labels are 1..n; slot 0 is unused
rank = [0] * (n + 1)
def top(x):
while up[x] != x:
up[x] = up[up[x]]
x = up[x]
return x
for a, b in edges:
ra, rb = top(a), top(b)
if ra == rb:
return [a, b]
if rank[ra] < rank[rb]:
ra, rb = rb, ra
up[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return []Why the first rejected edge satisfies the tie-break
Edges off the loop never close anything, because without the loop the graph is a tree. Loop edges are harmless until the last of them arrives: before that, the loop edges seen so far form an open path, not a circle. The moment the final loop edge (by list position) is processed, its endpoints are already joined along the rest of the loop, so union-find rejects it. That is exactly the latest removable edge, which is what the tie-break asks for.
Alternative: peel the leaves, then read the loop
If union-find feels like a trick, there is a direct way to find the loop. Count each node's degree. Any node with degree one is a leaf and cannot be on the loop, so remove it and lower its neighbor's degree, which may create a new leaf. When no leaves remain, the surviving nodes are exactly the loop. Then scan the edge list backward and return the first edge whose endpoints both survived. With a single loop, an edge between two surviving nodes must be a loop edge.
#include <array>
#include <vector>
std::array<int, 2> findRedundant(const std::vector<std::array<int, 2>>& edges) {
const int n = static_cast<int>(edges.size()); // nodes are 1..n
std::vector<std::vector<int>> adj(n + 1);
std::vector<int> degree(n + 1, 0);
for (const auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
++degree[e[0]];
++degree[e[1]];
}
std::vector<int> leaves;
for (int v = 1; v <= n; ++v)
if (degree[v] == 1) leaves.push_back(v);
while (!leaves.empty()) {
int v = leaves.back();
leaves.pop_back();
degree[v] = 0; // mark as removed
for (int u : adj[v])
if (degree[u] > 0 && --degree[u] == 1) leaves.push_back(u);
}
for (int i = n - 1; i >= 0; --i)
if (degree[edges[i][0]] > 0 && degree[edges[i][1]] > 0) return edges[i];
return {0, 0};
}This version also answers a common follow-up for free: list every removable edge. They are all the edges whose endpoints both survive the peeling.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Remove from the end, test connectivity | O(n²) | O(n) |
| Union-find, rank plus path halving | O(n α(n)), effectively linear | O(n) |
| Leaf peeling plus backward scan | O(n) | O(n) |
Edge cases to try
- The smallest possible input: three nodes in a triangle. Every edge is removable, so the last one is returned.
- A loop through every node, with no branches hanging off it.
- A long tail of nodes hanging off a small loop, where the last listed edge is in the tail.
- The extra edge listed first in the input, so the answer is some other loop edge.
- Edges written with endpoints in either order, such as [4, 1] instead of [1, 4].
Mistakes to avoid
- Returning the last edge in the list without checking that it is on the loop.
- Sizing the union-find arrays for n entries when labels run from 1 to n.
- Merging the endpoints themselves rather than their roots.
- Using a recursive find on a long chain without compression or ranks, which can hit the recursion limit.
- Explaining the union-find answer without the argument for why it respects the tie-break.
Follow-ups
- The edges are directed and the original was a rooted tree. Now the extra edge can either give some node two parents or create a directed loop, or both. Handle the two-parent case first by testing each of that node's incoming edges as the candidate, then fall back to loop detection.
- Several extra edges were added. For a connected graph with E edges, you must remove E - (n - 1) of them. If edges have costs and you want to keep the cheapest tree, that is a minimum spanning tree, and Kruskal's algorithm uses the same union-find.
- Return every removable edge. Use the leaf-peeling version; the survivors are the loop.
How to explain it out loud
Fictional example
- Candidate
- A tree plus one edge has exactly one loop, and only loop edges can be removed. So I need the loop edge that appears last in the list.
- Candidate
- I add edges in order with union-find. Off-loop edges always merge two groups. Loop edges also merge until the last one shows up, because before that they only form an open path.
- Candidate
- The first edge whose endpoints already share a root is therefore the final loop edge in list order, which is what the tie-break wants. With union by rank it is close to linear.
- Interviewer
- Can you do it without union-find?
- Candidate
- Yes. Strip degree-one nodes until none remain; what is left is the loop. Then scan the edges backward and return the first one with both ends on the loop.
Related problems
Graph Valid Tree asks the yes or no version: is the graph already a tree? Number of Connected Components runs the same merges to completion and counts groups. For a different graph skill, Word Ladder and Network Delay Time both measure distances. The algorithm interview questions guide mentions union-find alongside other graph techniques such as spanning trees.
Natively as a study aid
The hard part here is the argument, not the code, so practice explaining it to someone. Natively runs on Mac and Windows; in a practice session it can read the problem from a screenshot and suggest union-find or leaf peeling, with a note on the tie-break. The transcript of your mock round shows afterward whether your proof that the first rejected edge is the right one came out clearly. More on using an AI interview assistant.
Questions people ask
How do you solve Redundant Connection?
Add the edges in order to a union-find structure. The first edge whose two endpoints already share a root closes the loop; return it. With union by rank and path compression or halving, this is effectively linear.
Why does union-find return the edge that appears last?
Only loop edges are removable. Loop edges keep merging separate groups until the last of them arrives, because before that they form an open path. So the first rejected edge is the latest loop edge in the list.
Can you solve Redundant Connection with DFS?
Yes. Either check, before adding each edge, whether its endpoints are already connected (O(n²)), or find the loop by repeatedly removing degree-one nodes and return the latest edge with both ends on it (O(n)).
What is Redundant Connection II?
The directed version: the original graph was a rooted tree and the extra edge can give a node two parents, create a directed loop, or both. It needs a case analysis on top of union-find.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
