AlgoInsight

DSA problem

Redundant Connection

MediumUnion FindPattern: Union Findtop150AmazonGoogleMicrosoftBloombergMeta

In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. Return an edge that can be removed so that the resulting graph is a tree of n nodes.

Because the original tree has exactly n - 1 edges and one extra edge is added, the resulting graph has n edges and exactly one simple cycle. Any edge on that cycle is a valid candidate for removal, but the problem asks for the edge that occurs last in the input — so we should iterate the edges in input order and return the first one that closes a cycle.

The Union Find (DSU) data structure is purpose-built for detecting cycles incrementally. We process each edge [u, v] in order: if find(u) == find(v) then u and v are already in the same component, so adding this edge would create a cycle — return it immediately. Otherwise we union(u, v) and continue.

The advantage of this approach over DFS is that we never have to rebuild the adjacency list each time we try to remove an edge. With path compression and union by rank, the entire algorithm runs in O(n * alpha(n)) ~ O(n) amortised time and uses O(n) extra space.

Examples

Example 1
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Explanation: The first two edges build a tree on nodes {1,2,3}. The third edge [2,3] closes a cycle (since 2 and 3 already share a root), so it is the redundant edge.
Example 2
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Explanation: Edges [1,2], [2,3], [3,4] form a path. Edge [1,4] then closes the cycle 1-2-3-4-1, so it is redundant. Edge [1,5] is processed later but [1,4] is the first redundant edge encountered.
Example 3
Input: edges = [[1,2],[2,3],[1,3]]
Output: [1,3]
Explanation: After processing [1,2] and [2,3], all three nodes share a root. Edge [1,3] closes the cycle, so it is returned.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

union-findgraphcycle-detection

Browse all DSA problems