Skip to content
ΣDSA Patterns
Menu
Language

Union Find

Guide 5 of 6 · Path 5 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
123

edges = [1-2, 1-3, 2-3]

Redundant connection: a tree on n nodes plus one extra edge. Return the extra edge that closes a cycle (last in input if several).

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Redundant Connection

Problem (restated)

Undirected graph that started as a tree of n nodes, then one extra edge was added. Return that redundant edge (the one that creates a cycle). If multiple answers, return the one that appears last in the input.

Intuition

Scan edges in order with Union-Find. The first edge whose endpoints share a root is the redundant one.

Approaches

Union-Find first cycle edge

Unverified
Time O(n)Space O(n)

Idea. parent[1..n]. For each [u,v], if Find(u)==Find(v) return edge; else union.

Walkthrough. [[1,2],[1,3],[2,3]] → [2,3] closes the triangle.

Trade-offs. Input order matters for “last” requirement, process left to right.

Solution
export function findRedundantConnection(edges: number[][]): number[] {
  const n = edges.length;
  const parent = Array.from({ length: n + 1 }, (_, i) => i);
  const find = (x: number): number => {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]!]!;
      x = parent[x]!;
    }
    return x;
  };
  for (const e of edges) {
    const a = find(e[0]!), b = find(e[1]!);
    if (a === b) return e;
    parent[b] = a;
  }
  return [];
}
export function findRedundantConnection(edges: number[][]): number[] {
  const n = edges.length;
  const parent = Array.from({ length: n + 1 }, (_, i) => i);
  const find = (x: number): number => {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]!]!;
      x = parent[x]!;
    }
    return x;
  };
  for (const e of edges) {
    const a = find(e[0]!), b = find(e[1]!);
    if (a === b) return e;
    parent[b] = a;
  }
  return [];
}

Template connection

Union-Find cycle detection.

Reflection