Union by size
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Union by size joins two groups by always attaching the smaller group under the leader of the bigger group. Fewer members end up one step deeper, trees stay shallow, and you also get the size of every group for free.
Practical use cases
- Web app: Largest community in a social app. An analytics page for a social network wants to show the size of the biggest friend community. By keeping a size next to every leader and updating it on each merge, the page reads the biggest number directly instead of counting members. The dashboard number is always current and costs nothing to read, however large the community grows.
- Web app: Biggest island in a map editor. In a level editor, a designer paints land tiles and the tool shows the area of the largest island. Merging by size keeps lookups short and each leader already stores the island area. Tile counts per island are known at every moment, so the "largest island" label updates while the designer paints.
- System: Network resilience and class merging. Operators check how big the largest connected part of a network is after failures, and student-grouping tools track the size of each merged class. Size tracking answers both without recounting. Adding the smaller size to the bigger one costs a single addition, and then the answer is always at hand.
The story: The Big Family Adopts the Small One
In Zoya's lane, two big joint families lived side by side, and Mr. Kapoor's family of two lived at the end. When the Diwali committee needed a single list of "who belongs to which family", every household had to report to a head.
A busy aunty asked, "When two families merge, who becomes the head, the bigger or the smaller?" Raju scratched his head. "If the small family's head becomes the boss of the big family, then sixty people must walk one extra step to reach the boss. If the big family's head stays the boss, only two people walk one extra step."
So the committee made a rule: the head of the larger family stays the boss. When the two heads have the same count, pick either. Whenever someone is attached, add their size to the boss's tally. Nobody ever had to count heads again, because the tally always had the answer.
This is union by size. It is a sibling of union by rank: instead of tracking a rough height, you track the real head-count, and the smaller group always goes under the larger one. The trees remain short, and as a bonus you learn each group's size instantly.
How to spot this problem, and where you need it
You need to merge groups efficiently and also know how big each group is, for example to find the largest group at any moment.
Signs you need it
- The question asks for the "size of the group" or "largest component" after each merge.
- You are recounting members each time someone asks how big a group is.
- Merging a big group into a small one makes a long chain and slows lookups.
- The problem has repeated union operations along with size queries.
Where to use it in a project
- Dashboards that report the largest cluster, community or island.
- Network monitors that report how much of the system is still connected.
The solution
Keep a size number for every leader, starting at 1. To merge, find both leaders, compare sizes, and attach the smaller group's leader under the larger one. Add the smaller size to the larger leader's size. Now every merge moves the fewest members one level deeper, and every group size is available instantly.
Payoff: Before: counting a 100,000-member group on each query. After: reading one stored number.
Explain it like I am 8
A big class and a tiny class are joining. If the tiny class moves into the big room, only a few kids change rooms. If the big class had to move, everyone would be grumbling. So always move the smaller group.
How it works, step by step
- Keep a size per root, starting at 1 (the root itself).
- Find both roots. If they are the same, nothing to do.
- Make the smaller one a child of the bigger one: if
size[ra] < size[rb]swap them first. - Add the sizes:
size[big] += size[small]. - Bonus:
size[find(x)]answers "how many people are in x's group?" instantly.
The code in four languages
PHP
<?php
class DSU {
public array $parent = [];
public array $size = [];
public function __construct(int $n) {
for ($i = 0; $i < $n; $i++) { $this->parent[$i] = $i; $this->size[$i] = 1; }
}
public function find(int $x): int {
while ($this->parent[$x] !== $x) $x = $this->parent[$x];
return $x;
}
public function union(int $a, int $b): bool {
$ra = $this->find($a);
$rb = $this->find($b);
if ($ra === $rb) return false;
if ($this->size[$ra] < $this->size[$rb]) { // make ra the bigger family
[$ra, $rb] = [$rb, $ra];
}
$this->parent[$rb] = $ra; // smaller joins bigger
$this->size[$ra] += $this->size[$rb]; // update the head-count
return true;
}
public function sizeOf(int $x): int { return $this->size[$this->find($x)]; }
}
$d = new DSU(7);
foreach ([[0, 1], [2, 3], [4, 5], [0, 2], [6, 4], [4, 0]] as [$a, $b]) $d->union($a, $b);
echo "parent: " . implode(", ", $d->parent) . "\n"; // 0, 0, 0, 2, 0, 4, 4
echo "family of 5 has " . $d->sizeOf(5) . " members\n"; // 7JavaScript
class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = Array(n).fill(1);
}
find(x) {
while (this.parent[x] !== x) x = this.parent[x];
return x;
}
union(a, b) {
let ra = this.find(a);
let rb = this.find(b);
if (ra === rb) return false;
if (this.size[ra] < this.size[rb]) { // make ra the bigger family
[ra, rb] = [rb, ra];
}
this.parent[rb] = ra; // smaller joins bigger
this.size[ra] += this.size[rb]; // update the head-count
return true;
}
sizeOf(x) { return this.size[this.find(x)]; }
}
const d = new DSU(7);
for (const [a, b] of [[0, 1], [2, 3], [4, 5], [0, 2], [6, 4], [4, 0]]) d.union(a, b);
console.log("parent: " + d.parent.join(", ")); // 0, 0, 0, 2, 0, 4, 4
console.log("family of 5 has " + d.sizeOf(5) + " members"); // 7Java
import java.util.*;
public class Main {
static class DSU {
int[] parent;
int[] size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
}
int find(int x) {
while (parent[x] != x) x = parent[x];
return x;
}
boolean union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (size[ra] < size[rb]) { // make ra the bigger family
int tmp = ra; ra = rb; rb = tmp;
}
parent[rb] = ra; // smaller joins bigger
size[ra] += size[rb]; // update the head-count
return true;
}
int sizeOf(int x) { return size[find(x)]; }
}
public static void main(String[] args) {
DSU d = new DSU(7);
int[][] pairs = {{0, 1}, {2, 3}, {4, 5}, {0, 2}, {6, 4}, {4, 0}};
for (int[] p : pairs) d.union(p[0], p[1]);
System.out.println("parent: " + Arrays.toString(d.parent).replaceAll("[\\[\\]]", "")); // 0, 0, 0, 2, 0, 4, 4
System.out.println("family of 5 has " + d.sizeOf(5) + " members"); // 7
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
type DSU struct {
parent []int
size []int
}
func NewDSU(n int) *DSU {
d := &DSU{parent: make([]int, n), size: make([]int, n)}
for i := range d.parent {
d.parent[i] = i
d.size[i] = 1
}
return d
}
func (d *DSU) Find(x int) int {
for d.parent[x] != x {
x = d.parent[x]
}
return x
}
func (d *DSU) Union(a, b int) bool {
ra, rb := d.Find(a), d.Find(b)
if ra == rb {
return false
}
if d.size[ra] < d.size[rb] { // make ra the bigger family
ra, rb = rb, ra
}
d.parent[rb] = ra // smaller joins bigger
d.size[ra] += d.size[rb] // update the head-count
return true
}
func (d *DSU) SizeOf(x int) int { return d.size[d.Find(x)] }
func main() {
d := NewDSU(7)
for _, p := range [][2]int{{0, 1}, {2, 3}, {4, 5}, {0, 2}, {6, 4}, {4, 0}} {
d.Union(p[0], p[1])
}
parts := make([]string, len(d.parent))
for i, v := range d.parent {
parts[i] = strconv.Itoa(v)
}
fmt.Println("parent: " + strings.Join(parts, ", ")) // 0, 0, 0, 2, 0, 4, 4
fmt.Printf("family of 5 has %d members\n", d.SizeOf(5)) // 7
}Time: O(log n) per find/union · Extra space: O(n). A person only moves one level deeper when their family at least doubles, and that can happen only a few times, so trees stay short.
Watch out for
- Updating
size[small]instead ofsize[big]. Only the new root keeps a meaningful size. - Reading
size[x]for a non-root. Always read it throughsize[find(x)]. - Mixing up rank and size in one class. Choose one rule per structure to avoid confusion.
Quick check
- Which root becomes the boss in union by size?
- Always the first argument
- The smaller index
- The smaller one
- The one with the larger size
- After merging roots with sizes 3 and 4, the new root's size is…
- 4
- 3
- 7
- 12
- A free bonus of tracking size is…
- Avoiding find
- Deleting members
- Sorting for free
- Knowing each group's head-count instantly