AAI Agentic Handbook
Problem 46 · Graphs

Redundant Connection (Union-Find)

MediumClassic DSA & systems
01Problem

A tree of n nodes had one extra edge added. Given the edge list, return the edge that can be removed to restore a tree; if several, return the one that appears last.

02Key insight

Process edges in order with union-find (path compression + union by rank); the first edge whose endpoints already share a root closes the cycle. The same DSU counts connected components as n minus successful unions.

03Solution

Try it first.

TimeO(E * alpha(V))
SpaceO(V)
tests.py · 3 passing
tests.pypython4 lines
assert find_redundant_connection([[1,2],[1,3],[2,3]]) == [2,3]
assert find_redundant_connection([[1,2],[2,3],[3,4],[1,4],[1,5]]) == [1,4]
d = DSU(5); d.union(0,1); d.union(3,4)
assert len({d.find(i) for i in range(5)}) == 3
04Staff-level follow-up

Edges arrive as a stream and you need live component counts? DSU handles inserts online in near-O(1); deletions need offline divide-and-conquer or a dynamic-connectivity structure.