← DSA
MEDIUM

Redundant Connection

PracticeNeetCode ↗LeetCode ↗

A tree with n nodes originally had n - 1 edges. One extra edge was added, creating exactly one cycle. Given the edges, return the edge that can be removed to restore a valid tree. If more than one edge would work, return the one that appears last in the input.

Example

Input edges = [[1,2],[1,3],[2,3]]
Output [2,3]

Key Pointers

Step-by-Step Analysis

  1. Initialize a Union-Find parent array, one entry per node.
  2. Process each edge (a, b) in input order: find the roots of a and b.
  3. If the roots are already equal, a and b were already connected — this edge is redundant, so return it immediately.
  4. Otherwise union the two components and continue to the next edge.

Complexity

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

Code

def findRedundantConnection(edges: list[list[int]]) -> list[int]:
    n = len(edges)
    parent = list(range(n + 1))

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for a, b in edges:
        root_a, root_b = find(a), find(b)
        if root_a == root_b:
            return [a, b]
        parent[root_a] = root_b

    return []

Code Explanation

How the solution above works, piece by piece.

  1. The input is a tree plus one extra edge. Process edges in order with Union-Find.
  2. For edge (a, b), find both roots.
  3. Same root: a and b are already connected by earlier edges, so this edge closes a cycle. It's the redundant one; return it.
  4. Different roots: merge the groups and continue.
  5. Because edges are processed in input order, the edge returned is the last one that creates the cycle, as the problem asks. Nearly O(n).

Visual Walkthrough

Running it on edges = [[1, 2], [1, 3], [2, 3]]:

trace102132startparent[x] = x223edge 1-2roots 1 ≠ 2 → parent[1] = 2233edge 1-3roots 2 ≠ 3 → parent[2] = 3233edge 2-3find(2) = find(3) = 3 → already connected → return [2, 3]
Shown: parent[1..3]. Edges 1–2 and 1–3 merge everything into one group, so when 2–3 arrives both ends already share root 3: that edge is redundant.
re-pointed rootsame root → cycle

Video Explanation

NeetCode — Redundant Connection, LeetCode 684