InterviewPrepKit

Home / Coding / Graphs

Redundant Connection

medium Original ↗
Solving tips
  • The graph is a tree plus one edge (exactly one cycle); the redundant edge is the one whose two endpoints are ALREADY connected when you try to add it.
  • Union-find in one pass: for each edge, if find(a)==find(b) that edge closes the cycle so return it, else union them; O(n*alpha(n)).
  • Because you scan edges left to right, the first cycle-closing edge you hit is automatically the last such edge in the input, satisfying the tie-break.
  • Pitfall: nodes are labeled 1..n so size the parent/rank arrays n+1, and keep path compression + union by rank so find stays near-constant.

Problem

Start with a tree of n nodes labeled 1 to n (a connected, acyclic, undirected graph with exactly n - 1 edges). Someone adds one extra edge, so you’re given n edges total in edges, where each edges[i] = [a, b] is undirected. The extra edge creates exactly one cycle.

Return the one edge that can be removed so the remaining graph is again a tree. If more than one answer exists, return the edge that appears last in the input.

Examples

  • edges = [[1,2],[1,3],[2,3]][2,3] — nodes 1,2,3 form a triangle; removing [2,3] (the last edge closing the cycle) leaves a valid tree.
  • edges = [[1,2],[2,3],[3,4],[1,4],[1,5]][1,4] — the cycle is 1–2–3–4–1; [1,4] is the last edge that completes it.
  • edges = [[1,2],[2,3],[1,3]][1,3] — triangle again; [1,3] is the last edge forming the cycle.

Constraints

  • n == len(edges), 3 <= n <= 1000
  • Nodes are labeled 1 to n; the graph is connected with exactly one cycle.
  • No self-loops and no repeated edges.

Think about it first

Hint 1 The graph is a tree plus one edge, so there is exactly one cycle. The "redundant" edge is any edge on that cycle — and the problem wants the one that comes last in the input.
Hint 2 Process edges in order. Keep track of which nodes are already in the same connected group. An edge is redundant precisely when its two endpoints are *already* connected — adding it would close a cycle.
Hint 3 Union-find (disjoint-set union) makes this one pass: `union` the endpoints of each edge; the first edge whose endpoints share a root is your answer. Because you scan in order, it's automatically the last such edge.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.