Dynamic connectivity
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Dynamic connectivity is the job of answering "are these two connected right now?" while new links keep arriving. With union-find, each new link is merged in a moment and each question is answered by comparing two leaders.
Practical use cases
- Web app: Live route availability on a metro map. A city metro site adds new stations and lines as they open and lets people ask whether they can travel from one station to another. Each new line merges two groups; each question compares two leaders, so answers stay instant as the network grows.
- Web app: Real-time monitoring of device links. An IoT dashboard shows sensors coming online and links forming. An operator clicks two devices and sees "connected" or "not connected" immediately, without the page re-scanning the whole network. Operators can click any two devices during an incident and trust the answer, since it is always up to date.
- System: Mesh networks and map editors. Wireless mesh networks and online map editors continuously get new links and need quick connection checks, the exact situation union-find is built for. Neither side re-reads the whole map, because every new link is just folded into the groups the system already holds.
The story: The Metro That Kept Growing
A new metro city was opening its tunnels one at a time over the year. Station managers received a stream of events: "Tunnel opened between Rajiv Chowk and Kashmere Gate", then a passenger's question, "Can I go from the old fort to the airport right now?", then another tunnel, then another question.
Raju's cousin worked at the help desk. At first he kept a huge map and, for every question, traced a path across it with his finger. During rush hour a hundred people asked at once, and his finger gave up. "There must be a faster way," he grumbled.
Mira saw the key detail: tunnels only ever get added. Groups of connected stations can only grow and merge, never split. That is the perfect job for Union-Find. A new tunnel is a union; a passenger's question is two finds compared. No map tracing.
This is dynamic connectivity in its easiest form: edges arrive over time, and you answer "are these two connected now?" in nearly constant time. (If tunnels could also close, the problem becomes much harder, and the fix is a different design that replays the history of events.)
How to spot this problem, and where you need it
Links keep being added over time and users keep asking whether two things are connected, so recomputing everything for every question is too slow.
Signs you need it
- Operations arrive mixed together: "add a link" and "are A and B connected?".
- You re-run a graph search (BFS or DFS) for each question and it gets slower as the network grows.
- Links are only added, they never get removed.
- The answer must be fresh at every moment, not computed once in a nightly job.
Where to use it in a project
- Live network, transport or sensor status pages in dashboards.
- Collaborative editors where users connect items and the app must instantly tell what is linked.
The solution
Keep one union-find structure alive. For an "add link" event, union the two items. For a "connected?" question, find both leaders and compare. Use path compression and union by size so every operation stays almost constant in cost. The structure updates itself as the network grows.
Payoff: Before: a full network search for every question (hundreds of ms). After: near-instant answers even after millions of new links.
Explain it like I am 8
Think of a growing web of ropes between treehouses. Every time someone ties a new rope, you tell the little notebook. When a friend asks "can I walk from my house to yours?", you just compare two names in the notebook, without checking the ropes.
How it works, step by step
- Start with every node in its own set.
- For an "add edge" event: call
union(a, b). It merges the two groups at once. - For a "connected?" query: compare
find(a)andfind(b). Equal means yes. - Process events in the order they arrive. Each one costs nearly constant time, so thousands per second are fine.
- Know the limit: plain Union-Find cannot remove an edge. For deletions, solve it offline with a "union-find with rollback" or similar plan.
The code in four languages
PHP
<?php
class DSU {
private array $parent = [];
private 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) {
$this->parent[$x] = $this->parent[$this->parent[$x]];
$x = $this->parent[$x];
}
return $x;
}
public function union(int $a, int $b): void {
$ra = $this->find($a);
$rb = $this->find($b);
if ($ra === $rb) return;
if ($this->size[$ra] < $this->size[$rb]) [$ra, $rb] = [$rb, $ra];
$this->parent[$rb] = $ra;
$this->size[$ra] += $this->size[$rb];
}
public function connected(int $a, int $b): bool { return $this->find($a) === $this->find($b); }
}
// A live stream of events: "add" opens a tunnel, "ask" is a passenger's question
$events = [
["add", 0, 1], ["ask", 0, 2], ["add", 1, 2], ["ask", 0, 2],
["add", 3, 4], ["ask", 2, 4], ["add", 2, 3], ["ask", 0, 4], ["ask", 0, 5],
];
$metro = new DSU(6);
foreach ($events as [$type, $a, $b]) {
if ($type === "add") {
$metro->union($a, $b);
} else {
echo "Can " . $a . " reach " . $b . "? " . ($metro->connected($a, $b) ? "yes" : "not yet") . "\n";
}
}JavaScript
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) {
this.parent[x] = this.parent[this.parent[x]];
x = this.parent[x];
}
return x;
}
union(a, b) {
let ra = this.find(a);
let rb = this.find(b);
if (ra === rb) return;
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
}
connected(a, b) { return this.find(a) === this.find(b); }
}
// A live stream of events: "add" opens a tunnel, "ask" is a passenger's question
const events = [
["add", 0, 1], ["ask", 0, 2], ["add", 1, 2], ["ask", 0, 2],
["add", 3, 4], ["ask", 2, 4], ["add", 2, 3], ["ask", 0, 4], ["ask", 0, 5],
];
const metro = new DSU(6);
for (const [type, a, b] of events) {
if (type === "add") {
metro.union(a, b);
} else {
console.log("Can " + a + " reach " + b + "? " + (metro.connected(a, b) ? "yes" : "not yet"));
}
}Java
public class Main {
static class DSU {
private final int[] parent;
private final 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) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
void union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return;
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra;
size[ra] += size[rb];
}
boolean connected(int a, int b) { return find(a) == find(b); }
}
public static void main(String[] args) {
// A live stream of events: "add" opens a tunnel, "ask" is a passenger's question
Object[][] events = {
{"add", 0, 1}, {"ask", 0, 2}, {"add", 1, 2}, {"ask", 0, 2},
{"add", 3, 4}, {"ask", 2, 4}, {"add", 2, 3}, {"ask", 0, 4}, {"ask", 0, 5},
};
DSU metro = new DSU(6);
for (Object[] ev : events) {
String type = (String) ev[0];
int a = (Integer) ev[1], b = (Integer) ev[2];
if (type.equals("add")) {
metro.union(a, b);
} else {
System.out.println("Can " + a + " reach " + b + "? " + (metro.connected(a, b) ? "yes" : "not yet"));
}
}
}
}Go
package main
import "fmt"
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 {
d.parent[x] = d.parent[d.parent[x]]
x = d.parent[x]
}
return x
}
func (d *DSU) Union(a, b int) {
ra, rb := d.Find(a), d.Find(b)
if ra == rb {
return
}
if d.size[ra] < d.size[rb] {
ra, rb = rb, ra
}
d.parent[rb] = ra
d.size[ra] += d.size[rb]
}
func (d *DSU) Connected(a, b int) bool { return d.Find(a) == d.Find(b) }
type event struct {
kind string
a, b int
}
func main() {
// A live stream of events: "add" opens a tunnel, "ask" is a passenger's question
events := []event{
{"add", 0, 1}, {"ask", 0, 2}, {"add", 1, 2}, {"ask", 0, 2},
{"add", 3, 4}, {"ask", 2, 4}, {"add", 2, 3}, {"ask", 0, 4}, {"ask", 0, 5},
}
metro := NewDSU(6)
for _, ev := range events {
if ev.kind == "add" {
metro.Union(ev.a, ev.b)
} else {
answer := "not yet"
if metro.Connected(ev.a, ev.b) {
answer = "yes"
}
fmt.Printf("Can %d reach %d? %s\n", ev.a, ev.b, answer)
}
}
}Time: O(1) amortized per event (practically) · Extra space: O(n). Each tunnel or question costs nearly constant time, which is why this scales to millions of live events.
Watch out for
- Trying to delete a tunnel by "undoing" a union. Plain Union-Find cannot split groups; plan deletions offline or use rollback.
- Rebuilding the whole structure on every query. The point of DSU is that it stays alive and only grows.
- Asking the question with
parent[a] == parent[b]instead of comparing roots fromfind.
Quick check
- A new tunnel opens between two stations. Which operation do you run?
- make-set again
- sort the stations
- find on one station
- union of the two stations
- How do you answer "can A reach B right now?"
- Trace every tunnel
- Compare find(A) and find(B)
- Re-run Kruskal
- Count stations
- What can plain Union-Find NOT do?
- Remove a connection
- Count groups
- Add a connection
- Answer connected queries