Redundant Connection
Problem
You start with a tree on n nodes labeled 1..n (a connected graph with no cycles) and then one extra edge is added between two nodes that were not already directly connected. You are handed the resulting n edges as a list edges, where edges[i] = [a, b] is an undirected edge, in some order.
Return an edge that can be deleted so that what remains is again a tree on all n nodes. If more than one edge would work, return the one that appears latest in edges.
- There are exactly as many edges as nodes, and at least three of each; a few thousand nodes at most.
- Endpoints are node labels in
1..n; no self-loops and no edge is listed twice. - The input always consists of one tree plus one additional edge, so a valid answer exists.
Examples
edges = [[4,5],[2,4],[1,2],[3,5],[1,3],[5,6]]→[1,3]. Nodes 1-2-4-5-3 form the only cycle;[5,6]hangs off it and is not removable.[1,3]is the last cycle edge in the input.edges = [[1,2],[1,3],[1,4],[2,4]]→[2,4]. The cycle is 1-2-4;[1,3]is a leaf edge, and[2,4]is the cycle edge listed last.edges = [[2,6],[1,6],[3,4],[3,6],[1,4],[5,2]]→[1,4]. Removing[1,6],[3,6],[3,4]or[1,4]all leave a tree;[1,4]comes latest.
Hints
- A tree with
nnodes has exactlyn - 1edges. What does adding one edge to a tree always create? - Process edges in input order. What is special about the moment you try to add an edge whose two endpoints are already reachable from each other?
- Union-find: the first edge that joins two nodes already in the same component is the answer.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.