InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Redundant Connection

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug