AlgoTales · Roadmap

Disjoint Set Union

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Disjoint Set Union keeps track of which items belong to the same group, and lets you merge two groups and ask "are these two together?" in almost no time. Each group has a leader, and everyone points towards it.

Practical use cases

  • Web app: Live friend-group counter. Links between users arrive one at a time as people accept requests. The app must say instantly whether two users are in the same circle and how many circles exist. Merging leaders on each accept keeps this answer ready without rescanning the network.
  • Web app: Duplicate detection while importing. While importing a customer file, rows sharing an email or phone are marked as the same person. Each row joins its matching group as it is read, so by the end of the file all duplicates share one leader id.
  • Web app: Seat or pixel selection in an editor. A drawing tool or seat map lets users click to join touching cells into regions. The tool merges region leaders on each click, and "are these in the same region?" is answered immediately.
  • System: Kruskal and network connectivity. Kruskal's cheapest-plan algorithm uses it to refuse loop-making links, and network tools use it to say if two machines are connected. It is the quiet helper inside many bigger algorithms, answering the question "same group or not?" so quickly that it is almost free.

The story: Captains of the School Trip

On the school trip, Mrs. Sharma's class of six was drifting into friend circles. At every stop, kids made new friends and two circles merged into one. Mrs. Sharma kept getting the same two questions: "Are Aarav and Zoya in the same circle?" and "Merge these two circles!"

Keeping a list of members for every circle was slow: merging meant copying names around. Mira had a neater idea. "Every circle has one captain. Everybody remembers just one person: their parent, someone closer to the captain. The captain points to themselves."

To check if two kids are friends, follow the parents up until you meet a captain. Same captain means same circle. To merge two circles, just make one captain follow the other. Done, nobody else moves! Zoya added two small tricks: let the smaller circle follow the bigger one, and after climbing, make everyone on the path point straight to the captain so the next climb is one step.

That is the Disjoint Set Union (also called Union-Find): a structure that tracks which things belong together, with two moves, find and union, both lightning fast.

How to spot this problem, and where you need it

Links between items keep arriving, and you must repeatedly answer "are these two already connected?" and merge groups, without re-searching the whole network each time.

Signs you need it

  • The problem has many operations of two kinds: "connect A and B" and "are A and B connected?", mixed together.
  • Re-running a BFS or DFS after every new link makes the app slow, as the data grows.
  • You only need to know about groups, not about the exact path between two items.

Where to use it in a project

  • Importers or cleaners that merge records into identity groups while reading a large file.
  • Real-time features that track connected groups as links are added, such as networks, regions and teams.

The solution

Keep an array parent where each item starts pointing to itself. To find the leader of an item, follow parent pointers until an item points to itself, and shorten the path on the way back so next time is faster (path compression). To join two items, find both leaders and make one point to the other, attaching the smaller group under the bigger one. Same leader means same group.

Payoff: Before: a full re-scan of 1 million links after each new friendship. After: each connect or check takes a few pointer jumps.

Explain it like I am 8

Every group of friends has a captain. If you want to know whether two kids are in the same team, ask each "who is your captain?" Same answer means same team. To join two teams, one captain just says "OK, I will follow you."

How it works, step by step

  1. Start: every item is its own captain. Keep an array parent where parent[i] = i.
  2. find(x): keep jumping to parent[x] until you reach someone whose parent is themselves. That is the captain.
  3. Path compression: while climbing, re-point the kids you pass closer (or directly) to the captain.
  4. union(a, b): find both captains. If they differ, make the captain of the smaller group follow the captain of the bigger one ("union by size").
  5. connected(a, b) is simply find(a) === find(b). Nothing else is needed.

The code in four languages

PHP

<?php
class DSU {
    private array $parent;
    private array $size;
    public int $groups;

    public function __construct(int $n) {
        $this->parent = range(0, $n - 1);        // everyone is their own captain
        $this->size = array_fill(0, $n, 1);
        $this->groups = $n;
    }
    public function find(int $x): int {
        if ($this->parent[$x] !== $x) {
            $this->parent[$x] = $this->find($this->parent[$x]);   // path compression
        }
        return $this->parent[$x];
    }
    public function union(int $a, int $b): bool {
        $ra = $this->find($a);
        $rb = $this->find($b);
        if ($ra === $rb) return false;           // already in the same circle
        if ($this->size[$ra] < $this->size[$rb]) { [$ra, $rb] = [$rb, $ra]; }
        $this->parent[$rb] = $ra;                // smaller circle follows the bigger
        $this->size[$ra] += $this->size[$rb];
        $this->groups--;
        return true;
    }
    public function connected(int $a, int $b): bool {
        return $this->find($a) === $this->find($b);
    }
}

$kids = new DSU(6);
$kids->union(0, 1);
$kids->union(2, 3);
$kids->union(4, 5);
$kids->union(1, 3);
echo '0 and 3 friends? ' . ($kids->connected(0, 3) ? 'yes' : 'no') . PHP_EOL;
echo '0 and 5 friends? ' . ($kids->connected(0, 5) ? 'yes' : 'no') . PHP_EOL;
echo 'Circles left: ' . $kids->groups . PHP_EOL;

JavaScript

class DSU {
  constructor(n) {
    this.parent = [...Array(n).keys()];   // everyone is their own captain
    this.size = new Array(n).fill(1);
    this.groups = n;
  }
  find(x) {
    if (this.parent[x] !== x) {
      this.parent[x] = this.find(this.parent[x]);   // path compression
    }
    return this.parent[x];
  }
  union(a, b) {
    let ra = this.find(a), rb = this.find(b);
    if (ra === rb) return false;                    // already in the same circle
    if (this.size[ra] < this.size[rb]) { [ra, rb] = [rb, ra]; }
    this.parent[rb] = ra;                           // smaller circle follows the bigger
    this.size[ra] += this.size[rb];
    this.groups--;
    return true;
  }
  connected(a, b) {
    return this.find(a) === this.find(b);
  }
}

const kids = new DSU(6);
kids.union(0, 1);
kids.union(2, 3);
kids.union(4, 5);
kids.union(1, 3);
console.log('0 and 3 friends? ' + (kids.connected(0, 3) ? 'yes' : 'no'));
console.log('0 and 5 friends? ' + (kids.connected(0, 5) ? 'yes' : 'no'));
console.log('Circles left: ' + kids.groups);

Java

public class Main {
    static class DSU {
        private final int[] parent;
        private final int[] size;
        int groups;

        DSU(int n) {
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;                      // everyone is their own captain
                size[i] = 1;
            }
            groups = n;
        }

        int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);        // path compression
            }
            return parent[x];
        }

        boolean union(int a, int b) {
            int ra = find(a), rb = find(b);
            if (ra == rb) return false;             // already in the same circle
            if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
            parent[rb] = ra;                        // smaller circle follows the bigger
            size[ra] += size[rb];
            groups--;
            return true;
        }

        boolean connected(int a, int b) {
            return find(a) == find(b);
        }
    }

    public static void main(String[] args) {
        DSU kids = new DSU(6);
        kids.union(0, 1);
        kids.union(2, 3);
        kids.union(4, 5);
        kids.union(1, 3);
        System.out.println("0 and 3 friends? " + (kids.connected(0, 3) ? "yes" : "no"));
        System.out.println("0 and 5 friends? " + (kids.connected(0, 5) ? "yes" : "no"));
        System.out.println("Circles left: " + kids.groups);
    }
}

Go

package main

import "fmt"

type DSU struct {
	parent []int
	size   []int
	groups int
}

func NewDSU(n int) *DSU {
	d := &DSU{parent: make([]int, n), size: make([]int, n), groups: n}
	for i := range d.parent {
		d.parent[i] = i // everyone is their own captain
		d.size[i] = 1
	}
	return d
}

func (d *DSU) Find(x int) int {
	if d.parent[x] != x {
		d.parent[x] = d.Find(d.parent[x]) // path compression
	}
	return d.parent[x]
}

func (d *DSU) Union(a, b int) bool {
	ra, rb := d.Find(a), d.Find(b)
	if ra == rb {
		return false // already in the same circle
	}
	if d.size[ra] < d.size[rb] {
		ra, rb = rb, ra
	}
	d.parent[rb] = ra // smaller circle follows the bigger
	d.size[ra] += d.size[rb]
	d.groups--
	return true
}

func (d *DSU) Connected(a, b int) bool {
	return d.Find(a) == d.Find(b)
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	kids := NewDSU(6)
	kids.Union(0, 1)
	kids.Union(2, 3)
	kids.Union(4, 5)
	kids.Union(1, 3)
	fmt.Println("0 and 3 friends? " + yesNo(kids.Connected(0, 3)))
	fmt.Println("0 and 5 friends? " + yesNo(kids.Connected(0, 5)))
	fmt.Println("Circles left:", kids.groups)
}

Time: O(α(n)) per operation, practically O(1) · Extra space: O(n). With the two tricks (union by size and path compression) the chain of parents stays so short that each step is effectively constant time.

Watch out for

  • Linking the kids instead of the captains in union. Always call find on both first.
  • Skipping union by size / path compression. The parents can then form one long chain and every find becomes slow.
  • Forgetting that DSU only merges: it cannot split a group back into two.

Quick check

  1. How do you check whether two kids are in the same circle?
    • Count the members of each circle
    • Compare their numbers
    • Compare their captains using find
  2. What does union(a, b) really change?
    • Every member of both circles
    • Only one captain's parent pointer
    • Nothing, it only reads data
  3. What does path compression do?
    • Points kids on the climbed path closer to the captain
    • Deletes circles with one kid
    • Sorts the kids by number