AlgoFrames

Union-find applications: connectivity, grouping, redundant edges

Add edges one by one and union-find merges components, revealing connectivity, groups and the edge that creates a cycle.

Before you start: Disjoint set union: find, union, rank, path compression.

The idea

Cables join computers one at a time. After each cable, which computers can talk, and did the cable just close a loop?

Network admins, Kruskal's algorithm and grouping problems all ask this. Union-find answers it as each edge arrives.

Intuition

A new edge D-E whose ends have different roots joins two groups. The group count drops by 1.

An edge A-D whose ends already share a root changes nothing. It closes a cycle, so it is redundant.

A and D were already connected by the path A-B-C-D. The new edge adds a second path, which is a cycle.

Complexity

Searching the graph after every edge costs O(E · (V + E)). Union-find does two finds per edge, about O(E α(V)) in total.

The parent and size arrays hold one entry per item, so the space is O(V).

Pitfalls

Redundant Connection numbers nodes 1 to n. Size the parent array n + 1, or subtract 1 from every node.

In Accounts Merge, two accounts with the same name may belong to different people. Union accounts that share an email, never by name.

Variations

Union-find only merges. To handle edge deletions, process the edges in reverse and turn each deletion into a union.

Code

Pseudocode

make each item its own set; groups ← n; cycleEdge ← none
for each edge (u, v) in order
  ru ← find(u), rv ← find(v)
  if ru = rv: cycleEdge ← (u, v)
  else: union(ru, rv); groups ← groups − 1
return groups and cycleEdge

Python

def merge_edges(n, edges):
    parent = list(range(n))
    size = [1] * n
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    groups, cycle_edge = n, None
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            cycle_edge = (u, v)
            continue
        if size[ru] < size[rv]:
            ru, rv = rv, ru
        parent[rv] = ru
        size[ru] += size[rv]
        groups -= 1
    return groups, cycle_edge

JavaScript

function mergeEdges(n, edges) {
  const parent = Array.from({ length: n }, (_, i) => i);
  const size = new Array(n).fill(1);
  const find = (x) => {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]];
      x = parent[x];
    }
    return x;
  };
  let groups = n, cycleEdge = null;
  for (const [u, v] of edges) {
    let ru = find(u), rv = find(v);
    if (ru === rv) {
      cycleEdge = [u, v];
      continue;
    }
    if (size[ru] < size[rv]) [ru, rv] = [rv, ru];
    parent[rv] = ru;
    size[ru] += size[rv];
    groups--;
  }
  return { groups, cycleEdge };
}

Cost at a glance

TimeO(E α(V))
SpaceO(V)
InputEdges arriving one at a time
OutputGroup count, groups, and the edges that close cycles

Practice problems (4)

Merge or cycle? Warm-up

Five items A to E start alone. Edges arrive in the order A-B, B-C, D-E, C-A, C-D, E-B. Each edge either merges two groups or closes a cycle. On a merge, the smaller group takes the larger group's root, and a tie keeps the first item's root.

Redundant connection Standard

A tree with nodes 1 to n got one extra edge, so edges has n edges and exactly one cycle. Return the edge that can be removed to leave a tree. If several edges qualify, return the one that appears last in edges. An empty edges list has no extra edge, so return [].

Accounts merge Standard

Each string in accounts is a name followed by emails, separated by single spaces, such as "John js@mail.com j00@mail.com". Two accounts belong to the same person when they share at least one email; this links transitively. Accounts with the same name may still be different people.

Return one string per person: the name, then all of that person's emails in sorted order (plain string order), separated by spaces. The people may be listed in any order.

Number of provinces Standard

There are n cities. isConnected[i][j] is 1 when cities i and j are directly linked and 0 otherwise. A province is a group of cities linked directly or through other cities. Return the number of provinces.

Related topics

Next on the path: Graphs: vertices, edges, directed, weighted, degree, paths