Union by rank
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Union by rank decides which leader goes under the other by comparing how tall each group tree is. Attaching the shorter tree under the taller one keeps the tallest tree from growing, so finding a leader never needs many steps.
Practical use cases
- Web app: Connectivity checker for a large map. A delivery app tracks which road segments are linked into one network, with millions of segments. Merging by rank keeps every chain to the leader short, so "can a rider get from A to B?" stays quick even after millions of joins. Riders see a route answer in the same moment whether the network has a thousand or a million segments.
- Web app: Region grouping in a game map editor. A browser map editor joins land tiles into regions as the user paints. Without care, repeated joins create one long chain of tiles. Attaching shorter under taller avoids this and keeps the editor smooth. The designer keeps painting without hitches, even after thousands of joins in any possible order.
- System: Algorithm libraries and image segmentation. Standard union-find libraries and image-segmentation tools use rank so the worst case never gets bad, no matter in which order the merges arrive. The rule is tiny, a single comparison before each merge, yet it prevents the worst slowdowns on unlucky inputs.
The story: The Short Ladder and the Tall Ladder
At Zoya's cousin's wedding, the decorators had two ladders: a short stepladder and a tall ladder. One decoration team needed to hang a lantern from a high beam, and the manager wanted to connect them: put one ladder on top of the other, forming a long tower.
"Which goes on top of which?" asked Zoya. The first time, the decorators stacked the tall ladder on the short one, and the tower wobbled at nine metres. The second time, someone put the short stepladder alongside the tall one, so the tall one was still the main climb and it never got taller.
In the Union-Find world it is just the same. When two teams merge, the root of one must go under the root of the other. If the tall tree goes under the short one, the whole structure gets taller and every find gets slower. If the short tree goes under the tall one, the height does not change at all.
So every root keeps a small number, its rank, which is a rough height. Lower rank goes under higher rank. If both are equal, pick either and bump that root's rank by one. This is union by rank.
How to spot this problem, and where you need it
After many merges, some groups turn into long chains, so finding the leader takes many steps and the structure slows down.
Signs you need it
- Your merge always attaches the first group under the second one, whatever their sizes.
- Find time increases noticeably as more merges happen, especially if merges come in a bad order.
- You see long straight chains when you print the parent array.
- The problem has many unions and queries, so the structure must stay fast.
Where to use it in a project
- Any connectivity engine for networks, maps or social graphs built on union-find.
- Library or utility code that must stay fast whatever input order it gets.
The solution
Store a rank (an estimate of height) for each leader. When merging, compare the ranks: attach the leader with the smaller rank under the one with the larger rank. If both are equal, pick either and increase the winner's rank by one. This stops trees from growing tall, so a find climbs only a few steps.
Payoff: Before: chains that could reach thousands of steps. After: paths of about 20 steps even with a million items.
Explain it like I am 8
When you join two Lego towers, put the shorter tower's base on the side of the taller tower, not on top of it. The tall one stays the same height, so nothing wobbles.
How it works, step by step
- Keep a rank per root, starting at 0. It is a rough height of that tree.
- Find both roots
raandrb. If equal, stop; they are already together. - Lower rank goes under higher rank: if
rank[ra] < rank[rb], setparent[ra] = rb(and the other way round). - On a tie, choose either one as boss and add 1 to its rank. Only a tie makes the tree taller.
- Ranks are not exact heights once path compression flattens the trees, and that is fine. They are only a guide, and they are never decreased.
The code in four languages
PHP
<?php
class DSU {
public array $parent = [];
public array $rank = [];
public function __construct(int $n) {
for ($i = 0; $i < $n; $i++) { $this->parent[$i] = $i; $this->rank[$i] = 0; }
}
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->rank[$ra] < $this->rank[$rb]) {
$this->parent[$ra] = $rb; // shorter goes under taller
} elseif ($this->rank[$ra] > $this->rank[$rb]) {
$this->parent[$rb] = $ra;
} else {
$this->parent[$rb] = $ra; // a tie: the tree gets one level taller
$this->rank[$ra]++;
}
return true;
}
}
$d = new DSU(6);
foreach ([[0, 1], [2, 3], [0, 2], [4, 0], [5, 3]] as [$a, $b]) $d->union($a, $b);
echo "parent: " . implode(", ", $d->parent) . "\n"; // 0, 0, 0, 2, 0, 0
echo "rank: " . implode(", ", $d->rank) . "\n"; // 2, 0, 1, 0, 0, 0JavaScript
class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = Array(n).fill(0);
}
find(x) {
while (this.parent[x] !== x) x = this.parent[x];
return x;
}
union(a, b) {
const ra = this.find(a);
const rb = this.find(b);
if (ra === rb) return false;
if (this.rank[ra] < this.rank[rb]) {
this.parent[ra] = rb; // shorter goes under taller
} else if (this.rank[ra] > this.rank[rb]) {
this.parent[rb] = ra;
} else {
this.parent[rb] = ra; // a tie: the tree gets one level taller
this.rank[ra]++;
}
return true;
}
}
const d = new DSU(6);
for (const [a, b] of [[0, 1], [2, 3], [0, 2], [4, 0], [5, 3]]) d.union(a, b);
console.log("parent: " + d.parent.join(", ")); // 0, 0, 0, 2, 0, 0
console.log("rank: " + d.rank.join(", ")); // 2, 0, 1, 0, 0, 0Java
import java.util.*;
public class Main {
static class DSU {
int[] parent;
int[] rank;
DSU(int n) {
parent = new int[n];
rank = 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;
}
boolean union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (rank[ra] < rank[rb]) {
parent[ra] = rb; // shorter goes under taller
} else if (rank[ra] > rank[rb]) {
parent[rb] = ra;
} else {
parent[rb] = ra; // a tie: the tree gets one level taller
rank[ra]++;
}
return true;
}
}
static String show(int[] a) {
return Arrays.toString(a).replaceAll("[\\[\\]]", "");
}
public static void main(String[] args) {
DSU d = new DSU(6);
int[][] pairs = {{0, 1}, {2, 3}, {0, 2}, {4, 0}, {5, 3}};
for (int[] p : pairs) d.union(p[0], p[1]);
System.out.println("parent: " + show(d.parent)); // 0, 0, 0, 2, 0, 0
System.out.println("rank: " + show(d.rank)); // 2, 0, 1, 0, 0, 0
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
type DSU struct {
parent []int
rank []int
}
func NewDSU(n int) *DSU {
d := &DSU{parent: make([]int, n), rank: make([]int, n)}
for i := range d.parent {
d.parent[i] = i
}
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
}
switch {
case d.rank[ra] < d.rank[rb]:
d.parent[ra] = rb // shorter goes under taller
case d.rank[ra] > d.rank[rb]:
d.parent[rb] = ra
default:
d.parent[rb] = ra // a tie: the tree gets one level taller
d.rank[ra]++
}
return true
}
func show(a []int) string {
parts := make([]string, len(a))
for i, v := range a {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, ", ")
}
func main() {
d := NewDSU(6)
for _, p := range [][2]int{{0, 1}, {2, 3}, {0, 2}, {4, 0}, {5, 3}} {
d.Union(p[0], p[1])
}
fmt.Println("parent: " + show(d.parent)) // 0, 0, 0, 2, 0, 0
fmt.Println("rank: " + show(d.rank)) // 2, 0, 1, 0, 0, 0
}Time: O(log n) per find/union · Extra space: O(n). A tree only grows taller when two equal ones meet, which means it can never become a long chain; its height stays small.
Watch out for
- Increasing rank every union. Only a tie raises the winner's rank.
- Updating rank of a non-root. Ranks only matter at roots.
- Trying to lower rank after path compression. Ranks are only a guide and are never decreased.
Quick check
- Roots have rank 1 and rank 3. Which goes under which?
- They merge into rank 4
- The rank 3 goes under rank 1
- The rank 1 goes under rank 3
- Either, it does not matter
- When does a rank increase?
- Only when two roots of equal rank are joined
- Only for rank 0
- When find is called
- At every union
- What is the benefit of union by rank?
- It avoids needing find
- It sorts the array
- It prevents tall chains so finds stay fast
- It removes roots