LeetCode 684 Redundant Connection - Implementation

The approach

Process edges with Union-Find. Return first edge where both endpoints share a root.

def findRedundantConnection(edges): n = len(edges) parent = list(range(n + 1))

def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x]

def union(x, y):
    parent[find(x)] = find(y)

for u, v in edges:
    if find(u) == find(v):
        return [u, v]
    union(u, v)

return []

O(nα(n))O(n \cdot \alpha(n)) time, O(n)O(n) space.