sagelearnai

Redundant Connection

Difficulty: Medium · Pattern: Union-Find · LeetCode #684

A tree with n nodes labeled 1 … n had one extra edge added, creating exactly one cycle. Given the n edges, return an edge whose removal leaves a tree. If several answers are possible, return the one that appears last in the input.

Examples

text
edges = [[1,2], [1,3], [2,3]]                  →  [2, 3]
edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]    →  [1, 4]

Hints

  1. Add edges one by one. When does an edge create a cycle?
  2. An edge (a, b) creates a cycle iff a and b are already connected.
  3. The first such edge you meet is also the last edge of the cycle in input order.

Approach

Process edges in order with a DSU. For edge (a, b), if find(a) == find(b), the edge closes the cycle, so return it. Otherwise union them. Since there is exactly one cycle, the first edge that closes it is the last of the cycle's edges in input order, which is what the problem asks for.

Complexity

Time: O(n·α(n)). Space: O(n).

Python solution
def findRedundantConnection(edges):
    parent = list(range(len(edges) + 1))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            return [a, b]
        parent[ra] = rb
    return []
JavaScript solution
function findRedundantConnection(edges) {
  const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);
  const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
  for (const [a, b] of edges) {
    const ra = find(a), rb = find(b);
    if (ra === rb) return [a, b];
    parent[ra] = rb;
  }
  return [];
}