SDE & MLE Prep

684. Redundant Connection

Problem

A tree with nodes 1…n had one extra edge added, creating a cycle. Given the edges, return an edge whose removal leaves a tree; if several qualify, return the one that appears last in the input.

Example: [[1,2],[1,3],[2,3]] → [2,3]

Constraints: 3 ≤ n ≤ 1000.

Process edges in order with Union-Find; the first edge whose endpoints are already connected closes a cycle → return it.

Complexity: O(E · α(V)).

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        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 []