Redundant Connection

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write redundantConnection(edges). An undirected graph started as a tree on n nodes numbered 1 to n, then gained one extra edge between two different nodes that weren't joined yet, so edges holds n pairs [a, b] and the graph has exactly one cycle. Return an edge whose removal leaves a tree on all n nodes. Every edge on the cycle qualifies, so return the one that comes last in edges, written as it appears there. For example, for [[1, 2], [1, 3], [2, 3]] the answer is [2, 3], and for [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]] it's [1, 4]. The checks include 100,000 edges, so removing each edge in turn and re-checking the graph is too slow. A union-find also needs path compression or union by size to be fast enough.

Your code must pass

  • Finds the extra edge in a small graph
  • Returns the cycle's edge that comes last
  • Returns the edge as written in edges
  • Is fast enough for 100,000 edges