AlgoMaster Logo

Redundant Connection

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Union-Find (Disjoint Set)

Intuition:

The goal of this problem is to identify an edge that, when added, creates a cycle in a graph that otherwise forms a tree. Trees have N nodes with exactly N-1 edges and no cycles, whereas adding an additional edge creates exactly one cycle.

The Union-Find data structure is ideal for this type of problem because it helps efficiently manage and detect the connected components of a graph. The idea is to iterate over each edge and try to union its two nodes. If the two nodes are already in the same connected component (same parent/root in Union-Find terms), adding the edge would create a cycle, and that's the redundant connection.

The steps are:

  1. Initialize a Union-Find structure for n elements.
  2. Iterate through each edge.
  3. For each edge, check if the two endpoints are in the same component using find.
  4. If they are not, union them.
  5. If they are, this edge is the redundant one.

Code: