AlgoTales · Roadmap

Union

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Union merges two groups into one by making one leader report to the other. Nobody else needs to change, since everyone already follows their leader, so merging two huge groups costs only a couple of steps.

Practical use cases

  • Web app: Merging duplicate customer records. A CRM finds that "R. Sharma" and "Rahul Sharma" are the same person and clicks merge. With union, the two record groups are joined by linking their leaders, so every old duplicate in either group is now treated as one customer without rewriting thousands of rows. Support staff never wait, since the merge is just one changed link between two group leaders.
  • Web app: Friend suggestions after a new friendship. When two users become friends, their whole friend circles become one connected community. Union links the two circle leaders, so "people you may know" can use the bigger group right away. Nobody has to be updated one by one, so a community of 100,000 joins another in the same moment.
  • System: Photo editing and land records. A magic-wand tool joins neighbouring similar pixels into one region, and land-record software merges plots into one holding. Each merge is a single union between two leaders. No member is touched individually, which is why merging stays cheap even when the groups are enormous.

The story: The Handshake of the Two Captains

In Mira's mohalla, kids played cricket in small gully teams. One evening two teams had too few players, so their captains agreed to merge. Kabir asked, "Do we have to re-write everyone's team on a big sheet?" With forty kids that sounded like an exhausting job.

Raju from the chai stall, who knew everyone, shook his head. "No need. Only the two captains shake hands. One captain tells the other: you are our boss now. Every player already knows their captain, so the whole team follows automatically."

There was one catch. A player cannot just say "I will join your team", because their own captain might already be on the other side. Raju was careful: "First find the captain of each player. If it is the same captain, they are already together. Do nothing! If different, connect the captains."

That handshake is union: find both roots, and if they differ, point one root to the other. A single changed pointer merges two whole groups.

How to spot this problem, and where you need it

Two groups must be combined into one as new links appear, and rewriting every member of the smaller group each time becomes slow as groups get large.

Signs you need it

  • Your code loops over all members of one group to change a group id whenever two groups merge.
  • Merges happen thousands of times, such as one per imported record or friendship.
  • The problem says "join", "merge", "connect" or "union of sets".
  • You only care which group something is in, not who exactly is in it.

Where to use it in a project

  • Record deduplication and customer merge tools in a CRM.
  • Social or network features where connections get added continuously.

The solution

Find the leader of each item involved. If the leaders are already the same, they are in one group and nothing needs doing. Otherwise make one leader point to the other. That single pointer change merges both complete groups. Combined with rules like union by size, it keeps lookups quick.

Payoff: Before: renaming every member of a group of 50,000 on each merge. After: changing one pointer.

Explain it like I am 8

Two clubs each have a leader. To make one big club, the two leaders agree that one of them now reports to the other. Nobody else has to move or change anything, because everyone already follows their leader.

How it works, step by step

  1. Find the root of a and the root of b: ra = find(a), rb = find(b).
  2. If ra == rb, they are already in the same team. Stop. This check also prevents loops.
  3. Otherwise make one root a child of the other: parent[ra] = rb.
  4. Nothing else is touched. Everyone under ra now finds rb as their top boss, with no extra work.
  5. Return whether you merged (true or false). That boolean becomes very useful for cycle detection and Kruskal later.

The code in four languages

PHP

<?php
class DSU {
    private array $parent = [];
    public function __construct(int $n) {
        for ($i = 0; $i < $n; $i++) $this->parent[$i] = $i;
    }
    public function find(int $x): int {
        while ($this->parent[$x] !== $x) $x = $this->parent[$x];
        return $x;
    }
    // union: connect two captains. Returns true if a merge really happened
    public function union(int $a, int $b): bool {
        $ra = $this->find($a);
        $rb = $this->find($b);
        if ($ra === $rb) return false;   // already the same team
        $this->parent[$ra] = $rb;        // one handshake merges two teams
        return true;
    }
    public function parents(): array { return $this->parent; }
}

$d = new DSU(6);
foreach ([[0, 1], [2, 3], [1, 3], [0, 2], [4, 5], [0, 5]] as [$a, $b]) {
    echo "union($a,$b) -> " . ($d->union($a, $b) ? "merged" : "already together") . "\n";
}
echo "parent: " . implode(", ", $d->parents()) . "\n";

JavaScript

class DSU {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i);
  }
  find(x) {
    while (this.parent[x] !== x) x = this.parent[x];
    return x;
  }
  // union: connect two captains. Returns true if a merge really happened
  union(a, b) {
    const ra = this.find(a);
    const rb = this.find(b);
    if (ra === rb) return false;   // already the same team
    this.parent[ra] = rb;          // one handshake merges two teams
    return true;
  }
}

const d = new DSU(6);
for (const [a, b] of [[0, 1], [2, 3], [1, 3], [0, 2], [4, 5], [0, 5]]) {
  console.log("union(" + a + "," + b + ") -> " + (d.union(a, b) ? "merged" : "already together"));
}
console.log("parent: " + d.parent.join(", "));

Java

import java.util.*;

public class Main {
    static class DSU {
        int[] parent;

        DSU(int n) {
            parent = new int[n];
            for (int i = 0; i < n; i++) parent[i] = i;
        }

        int find(int x) {
            while (parent[x] != x) x = parent[x];
            return x;
        }

        // union: connect two captains. Returns true if a merge really happened
        boolean union(int a, int b) {
            int ra = find(a);
            int rb = find(b);
            if (ra == rb) return false;   // already the same team
            parent[ra] = rb;              // one handshake merges two teams
            return true;
        }
    }

    public static void main(String[] args) {
        DSU d = new DSU(6);
        int[][] pairs = {{0, 1}, {2, 3}, {1, 3}, {0, 2}, {4, 5}, {0, 5}};
        for (int[] p : pairs) {
            System.out.println("union(" + p[0] + "," + p[1] + ") -> "
                    + (d.union(p[0], p[1]) ? "merged" : "already together"));
        }
        System.out.println("parent: " + Arrays.toString(d.parent).replaceAll("[\\[\\]]", ""));
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type DSU struct {
	parent []int
}

func NewDSU(n int) *DSU {
	parent := make([]int, n)
	for i := range parent {
		parent[i] = i
	}
	return &DSU{parent: parent}
}

func (d *DSU) Find(x int) int {
	for d.parent[x] != x {
		x = d.parent[x]
	}
	return x
}

// Union connects two captains. It returns true if a merge really happened.
func (d *DSU) Union(a, b int) bool {
	ra, rb := d.Find(a), d.Find(b)
	if ra == rb {
		return false // already the same team
	}
	d.parent[ra] = rb // one handshake merges two teams
	return true
}

func main() {
	d := NewDSU(6)
	for _, p := range [][2]int{{0, 1}, {2, 3}, {1, 3}, {0, 2}, {4, 5}, {0, 5}} {
		result := "already together"
		if d.Union(p[0], p[1]) {
			result = "merged"
		}
		fmt.Printf("union(%d,%d) -> %s\n", p[0], p[1], result)
	}
	parts := make([]string, len(d.parent))
	for i, v := range d.parent {
		parts[i] = strconv.Itoa(v)
	}
	fmt.Println("parent: " + strings.Join(parts, ", "))
}

Time: O(h), up to O(n) · Extra space: O(1). Two finds plus one pointer change. The finds dominate, so keeping trees short matters next.

Watch out for

  • Setting parent[a] = b directly. If a is not a root, you cut a away from its own team and lose everyone else in it. Always link roots.
  • Skipping the same-root check. Linking a root to itself, or to its own descendant, creates a loop that makes find run forever.
  • Always linking ra under rb blindly can build a tall skinny chain. Union by size or rank fixes it.

Quick check

  1. What do you connect in a union?
    • The two roots (captains)
    • The first and last item
    • All members
    • The two items directly
  2. union(0, 2) is called when 0 and 2 already share a root. What happens?
    • The array resets
    • A loop forms
    • Nothing; it returns false
    • Both become roots
  3. How many pointers change in one successful union?
    • Two
    • The size of the team
    • All of them
    • One