#684

Redundant Connection

Medium Union-Find

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A tree with n nodes had one extra edge added. Return an edge that can be removed to leave a tree (if several, the one that appears last in the input).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: which extra edge turned the tree into a graph with a cycle?

Why this works: add edges with Union-Find; the first edge whose ends are already connected closes the cycle.

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

1-2 join, 1-3 join, 2-3 already connected → [2,3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Skipping path compression — still correct, but finds can become slow on long chains.

Solve on LeetCode ↗
Complexity
  • Time: O(n · α(n)) ≈ O(n).
  • Space: O(n).
Topic: Graphs
🎬 Episodes 74–85: video coming soon