TRT
Sign in
mediumAdvancedLeetCode#union-find#cycle detection

Redundant connection

Find the edge that closes the only cycle in a graph that was a tree plus one extra edge, with union-find.

The Runtime Theory Team1 min read
Taught inDisjoint setsPro — members onlyUnion-find keeps elements in groups that only ever merge. Each group is a tree of parent pointers, its root names the group, and two questions, which group is x in and merge these two groups, cover a surprising range of problems.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inedges = [[1, 2], [1, 3], [2, 3]]

out[2, 3]

inedges = [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]

out[1, 4]

inedges = [[1, 2], [2, 3], [3, 1]]

out[3, 1]

A graph on vertices 1 to n started as a tree, and then one extra edge was added. Return an edge that can be removed so the graph becomes a tree again. If several answers exist, return the one that appears last in the input.

Before you code

The extra edge created exactly one cycle. Which edge of that cycle is the last one to appear in the input, and what happens at the moment it is processed?

Hints

  1. Process the edges in input order, with one union-find group per vertex.
  2. Union the endpoints of each edge. While unions succeed, the edges so far form a forest.
  3. The first edge whose endpoints already share a root closes the cycle, and it is the last of the cycle's edges in the input. Return it.

Production & complexity notes

When solving Redundant connection on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Disjoint sets to reinforce the underlying pattern.

What it practices

Cycle detection with union-find, from Disjoint sets.

Not started

Sign in to save your learning progress.

Sign in to save