~/problems / Weighted graphs / Union-Find

Redundant Connection

medium ~20 min

A tree on nodes 1 .. n had one extra undirected edge added, so now there are n edges and exactly one cycle. edges lists them as [u, v] pairs (no duplicates, no self-loops).

Write find_redundant_connection(edges) -> list[int] that returns an edge whose removal leaves a tree on all n nodes. Several edges on the cycle qualify; return the one that appears last in edges, as it's written there ([u, v], same order).

find_redundant_connection([[1, 2], [1, 3], [2, 3]])                   # [2, 3]
find_redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]])   # [1, 4]

Constraints: 3 <= n <= 50_000, len(edges) == n, 1 <= u, v <= n. Running a separate search for each edge is too slow at this size; aim for near-linear time.

Show hint

add the edges one at a time while tracking which nodes are already connected. The first edge that joins two nodes that are already connected closes the cycle; think about why it is also the last cycle edge in the list.

Topic: Union-Find. Path compression + union by rank; connectivity and grouping.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc