Skip to problem
←

Redundant Connection

Medium 0 attempts

An undirected tree on vertices 1 through n gained one additional edge between two different vertices. You receive the resulting n edges in edges.

Return an edge whose removal leaves a connected tree. If more than one edge qualifies, return the one appearing latest in the input list, preserving its endpoint order. The input order does not identify which edge was originally added.

Only edges on the graph's single cycle can be removed without disconnecting it. The last edge in the entire list need not be on that cycle.

For [[1,2], [2,3], [3,4], [1,4], [1,5]], return [1,4]. It is the latest cycle edge; removing the later edge [1,5] would isolate vertex 5.

Function contract

Implement findRedundantConnection(edges).

Output: Return the removable edge appearing latest in edges, as [u, v] in its input endpoint order.

Example 1

Input
edges = [[1,2],[1,3],[2,3]]
Output
[2,3]

Example 2

Input
edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output
[1,4]
Constraints
  • n == edges.length
  • 3 <= n <= 1000
  • 1 <= edges[i][0] < edges[i][1] <= n
  • Edges are distinct and form a connected undirected graph obtained by adding one edge to a tree on vertices 1 through n.

Union-Find in Input Order

Initially every vertex is its own component. Process edges in their given order. If the endpoints belong to different components, join them using union by size. Path compression keeps future representative lookups fast.

If both endpoints are already connected, an earlier path joins them, so the current edge closes a cycle. Return that edge.

Why does the first cycle-closing edge satisfy the latest-edge rule? There is exactly one cycle in the full graph. No cycle edge closes it until all the other cycle edges have appeared, so the detected edge is precisely the latest member of that cycle. Later non-cycle edges do not qualify for removal.

javascript
function findRedundantConnection(edges) {
  const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);
  const size = Array(parent.length).fill(1);
  function find(x) {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]];
      x = parent[x];
    }
    return x;
  }
  function union(a, b) {
    a = find(a);
    b = find(b);
    if (a === b) return;
    if (size[a] < size[b]) [a, b] = [b, a];
    parent[b] = a;
    size[a] += size[b];
  }
  for (const [u, v] of edges) {
    if (find(u) === find(v)) return [u, v];
    union(u, v);
  }
}

Time: O(n α(n)) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript