progress

~/problems / Weighted graphs / Union-Find

Redundant Connection

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

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], [2, 3], [3, 4], [1, 4], [1, 5]])   # [1, 4]
Five nodes where 1, 2, 3 and 4 form a square cycle and 5 hangs off 1; of the cycle edges, 1-4 is listed last, so it is the redundant one.
find_redundant_connection([[1, 2], [1, 3], [2, 3]])                   # [2, 3]

Constraints: 3 <= n <= 50_000, len(edges) == n, 1 <= u, v <= n.

⭐ Bonus: a speed test with 50,000 edges earns a star in near-linear time. Running a separate search for each edge is too slow for it.

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