Union-find and the inverse Ackermann function
Analyze union-find, rank and path compression, inverse Ackermann bounds, and incremental and offline connectivity.
After this lesson you can
- Implement union-find iteratively with union by size and path compression.
- Prove union by rank bounds height by log₂ n.
- Prove the O(m log* n) bound and explain the idea behind the α(n) bound.
- Solve incremental and offline connectivity problems with union-find.
- Recognize when union-find does not apply, such as online edge deletion.
Before you start
Motivation: a partition that only merges
A graph grows one edge at a time and at every moment must answer a question: are and in the same connected component? Recomputing components by depth-first search after every edge costs per query, and with edges takes steps. But the question has special structure: components only merge, never split, allowing a data structure whose operation costs practically a constant.
The same pattern appears in places that seem unrelated:
- Percolation and image processing. A grid of pixels or cells fills up and we need to know which cells form a connected region, or whether a region touches opposite boundaries. We will see this with a Monte Carlo simulation and binary-image component labeling.
- Minimum spanning trees. Kruskal’s algorithm (graph lesson) traverses edges by weight and needs to know whether an edge closes a cycle, meaning whether its endpoints are already connected.
- Unification and congruence closure. SMT solvers (congruence closure) and type-inference unification maintain equivalence classes of terms as they are identified.
- Clustering. Hierarchical clustering’s single linkage is Kruskal in disguise, and grouping near-duplicate pairs after locality-sensitive hashing is a chain of unions.
The lesson aims to understand, with proof, why two one-line heuristics (linking by rank and path compression) bring amortized cost to , where is the inverse Ackermann function: a function not exceeding 4 while is a number that fits in the universe. Also understand the guarantee’s limits: it is neither strictly constant nor applicable when edges must be deleted online.
The problem and first analysis
A partition of a set is a family of nonempty disjoint subsets whose union is ; it is equivalent to an equivalence relation on whose classes are the blocks. Merging two blocks is equivalent to adding a pair to the relation and taking closure. For the growing-graph problem, the class of is its connected component (paths and connectivity) and adding edge merges the classes of and .
The two simplest solutions fail on opposite sides. An array etiqueta[x] storing each element’s representative gives find in , but union must relabel a whole block: . An uncareful tree links two roots in , but its find can cost . The first analysis balancing both uses linked lists with weighted union: each block is a list whose nodes store its representative, and union relabels the shorter list’s elements and concatenates it to the longer.
Proof
find and make_set cost , and each union costs plus the number of relabeled elements. Fix an element : whenever relabeled, its block belonged to the shorter union list, so ‘s block at least doubles. Since no block exceeds elements, is relabeled at most times. Summing over elements gives at most relabelings.
This is an amortized bound in the sense of the previous amortized-analysis lesson: a particular union can move elements, but the total is bounded. The key idea, “move the smaller”, will return in another guise. One jump remains: from total to nearly .
Pointer forests
Galler and Fischer (1964) proposed storing each block as a rooted tree (rooted tree) where each node points to its parent and the root points to itself. The representative is the root. The entire structure is an array padre:
find(x): follow pointers upward to the root.union(x, y): find the two roots and and, if different, link one below the other (padre[a] = b).
Without further care the tree can degenerate: union(0,1), union(1,2), ... with the link “hang the first root under the second” builds a chain of nodes and the next find(0) follows pointers. We measure operation cost as the number of pointers followed by find.
There are two independent improvements, and the figure shows what each fixes. The first prevents trees from growing tall during linking; the second repairs tall trees when traversed.
Union by rank and size
Without compression, a node’s rank is exactly its subtree height; with compression it becomes a surviving upper bound on that height: compression shortens trees but does not touch rank. With rank, the tallest tree grows only when two equally tall trees merge, requiring the node count to double.
Proof
Induct on the number of links to show for every and that the height of (maximum distance to a leaf in its subtree) is at most . Initially and height is 0. Consider a link of root below root with .
- If , the rank of does not change, its size grows and its height becomes because .
- If ranks both equal , the rank of becomes , its size at least and its height .
Other nodes change neither rank nor subtree. Since , follows, as does the height bound.
∎Union by size gives the same result with an even more direct proof: a node drops one level only when its tree joins another at least as large, so its tree doubles, and this can happen at most times. With rank or size, any sequence of operations costs , and the bound is attained: merging equal-sized binomial trees yields a tree of exact height .
Path compression
There is another way to exploit the fact that find already traverses a path to the root: make that path shorter next time.
The standard version, full compression, makes two passes (one to find the root, one to redirect). Two one-pass variants need neither recursion nor a second pass and are therefore used in practice:
- Path splitting: each visited node points to its grandparent, and traversal continues through the original parent.
- Path halving: each visited node points to its grandparent and traversal continues through the grandparent, skipping alternate nodes.
All three have the same asymptotic bounds shown below. Try them in the previous figure: they change forest shape (full compression flattens it at once, the other two flatten it in halves), but not cost order of magnitude.
Compression alone. Without union by rank, compression already helps greatly: in the figure’s chain, the first search pays pointers and subsequent searches one. But it is not enough. Fischer (1972) and Tarjan and van Leeuwen (1984) showed that with arbitrary linking and compression, worst-case cost is ; for it is . The extreme example is a binomial tree (a node ; is a root with children , with nodes and depth ), with a new root added above and a search from the deepest leaf: compression reorganizes the tree but leaves it shaped like an again (with an extra leaf or so), so the next new root again creates a path of length . Each round costs and the tree hardly changes; you will prove this in an exercise and the figure reproduces it with the ‘Binomial’ sequence.
The heuristics complement each other: rank prevents tall trees from the start and compression makes heavily traversed paths cheap. Tarjan’s theorem says together they give amortized . The route there passes through an intermediate, easier-to-prove bound that is already almost linear.
The bound
The iterated logarithm is the number of times must be applied to reach or less:
It grows so slowly that (because ) and . The proof uses three rank properties valid with any mixture of compressions, because compression does not touch ranks.
Proof
(1) Rank changes only in a root receiving a child of the same rank. (2) On linking, root hanging under has lower rank than or, if equal, ‘s rank increases by 1, so in both cases . Compression redirects node to root of the path (or, in splitting and halving, to its grandparent), a proper ancestor of ‘s old parent and, by monotonicity along that path, of strictly higher rank; if the parent was already root, nothing changes. (3) Reason about the link forest that would result ignoring compressions: its subtrees are those of the preceding theorem and every node of rank has at least descendants. Two nodes of the same rank cannot be ancestors of one another (by strict monotonicity), so their subtrees are disjoint and at most nodes have rank . Summing the geometric series gives .
∎Now group ranks into blocks whose lengths grow as a power tower. Let and : . Block contains ranks and block contains ranks : , , , , etc. Since maximum rank is , the number of blocks used satisfies .
Proof
Each union consists of two find and of linking, so it suffices to bound pointers followed by the find. In one find, let be the path to the root. Each pointer () is charged as follows:
- Type C: if is the root, charge it to
find. This is one pointer per search. - Type A: if is not root and is in a higher block than , charge it to
find. Ranks increase along the path, so block index does not decrease and this occurs at most times per search. - Type B: if is not root and is in the same block as , charge it to node .
A and C charges total at most per search, overall. For B charges, consider node in block . Whenever charged, its parent is not root and compression redirects it to the root, whose rank is strictly higher than its previous parent’s. While the parent stays in block , this can repeat at most once per block rank above its own: fewer than times. Once its parent moves to a higher block, all future charges to are type A. Thus:
- Block : at most nodes, each receiving at most 1 B charge (rank 0 to rank 1): .
- Block (rank ) cannot have B charges: parent rank is strictly greater.
- Block : by the lemma at most nodes have rank and each receives fewer than B charges, so the whole block receives fewer than .
B charges therefore total at most , and total cost is .
∎Everything needed from this proof is in the next figure, which actually counts charges of each type on a real forest: number of nodes of each rank (bars, logarithmic scale) against the lemma’s bound, and each block’s type B charges (solid bars) against its bound (outline). In the tournament the rank lemma is attained up to a factor of 2, but charges remain several times below their bounds in both modes: the proof is worst-case and does not predict typical cost.
Ackermann’s function and its inverse
The bound can improve because block reasoning has a weak point: a factor is lost within a block and can be recovered using finer, recursively refined blocks. After Tarjan’s work (1975), the result is a function growing more slowly than any iteration of , defined using the Ackermann hierarchy.
It is a staircase. and have closed forms, and with them
The next step no longer fits anywhere: . Since , this quantity is at least a tower of twos, . Therefore for , for , for , for and for . For any that can be written, copied or counted with atoms, . Literature also uses a two-argument form , depending on density and smaller still when ; for , is a valid upper bound on it.
The full proof takes several pages (CLRS, chapter 19 of the fourth edition, section “Analysis of union by rank with path compression”). The idea is a potential refining blocks into levels. For a non-root node of rank , with parent , define:
The level says how high on the Ackermann staircase the parent’s rank is relative to the child’s, and iteration says how many times was applied. Since and , we have and . The potential of is if is root or has rank , and otherwise. Since , total potential is at most .
The heart of the proof is the following lemma, which can be proved from what we already have.
Proof
Let before compression. Since is an ancestor of or is , . Since , . After compression the new parent of is the root, whose rank is . Since is increasing,
There are two cases. If remains , then and falls by at least 1. If rises, the new parent rank reaches or more, and with new level and new iteration , , whereas before it was because : it also falls by at least 1.
∎Now count. On a path of nodes, these cannot decrease potential: the root, the rank- node (at most one by rank monotonicity), and at most the last node of each level, of which there are at most . Every other path node reduces potential by at least 1. Amortized search cost is . Two full-proof details remain: compression never increases any node’s potential, and linking two roots changes total potential by . Then operations cost plus initial potential, when starting from isolated nodes.
Top-down analysis. Seidel and Sharir (2005) gave a proof that changes direction. Rather than construct a decreasing potential, they start from a monotone-rank forest and compressions and define maximum cost of compressing paths in an -node forest with ranks. Cut the forest at rank : low trees (ranks below ) and the high forest (ranks at least that). Each compression path splits into a low segment and, if it reaches it, a high segment. High segments form an instance of the same problem with ranks, at most compressions and many fewer nodes (by the rank lemma, at most ), so a coarse bound suffices. Paths that do not leave low trees form another instance with only ranks. In paths that rise, the low segment is charged directly: for the edge crossing into the high forest and per low node which, upon compression, becomes a child of the high forest, something each node does once. The resulting recurrence has form . Applied repeatedly with cuts chosen by the Ackermann staircase steps, each pass improves the preceding bound by one hierarchy level, and the number of passes needed is on the order of . This is an outline: the recurrence is not solved here, and details are in the paper. The same method also gives Tarjan and van Leeuwen’s upper bound for compression without rank.
Can it be improved? No: the bound is optimal. Tarjan (1979) proved that in the pointer-machine model any separable algorithm (those that, like this one, link only nodes of the same set) needs , and Fredman and Saks (1989) proved amortized per operation in the cell-probe model for any structure, with -bit words. Thus is not an artifact of analysis: it is the problem’s true cost.
Implementation from scratch
First, the complete structure with three compression variants and a pointer counter, and the figure’s experiment with larger : a random sequence, a chain with repeated searches, and the binomial sequence. Everything is iterative: recursive find overflows on a long path before compression can act (by default, Python gives up at 1000 levels).
import random
class UnionFind:
"""Union-find con heurísticas elegibles y contador de punteros seguidos (aristas de los caminos de búsqueda)."""
def __init__(self, n, por_tamano=True, compresion="completa"):
self.padre = list(range(n))
self.tam = [1] * n
self.por_tamano = por_tamano
self.compresion = compresion # "ninguna", "completa" o "mitad"
self.punteros = 0 # coste acumulado
self.mayor = 0 # coste de la búsqueda individual más cara
def buscar(self, x):
p = self.padre
pasos = 0
if self.compresion == "mitad": # reducción a la mitad: un solo recorrido, sin recursión
while p[x] != x:
papa = p[x]
abuelo = p[papa]
pasos += 1 if abuelo == papa else 2
p[x] = abuelo
x = abuelo
raiz = x
else:
raiz = x
while p[raiz] != raiz:
raiz = p[raiz]
pasos += 1
if self.compresion == "completa":
while p[x] != raiz: # segunda pasada: todos los del camino apuntan a la raíz
siguiente = p[x]
p[x] = raiz
x = siguiente
self.punteros += pasos
self.mayor = max(self.mayor, pasos)
return raiz
def unir(self, x, y):
a, b = self.buscar(x), self.buscar(y) # se unen las RAÍCES, no los elementos
if a == b:
return False
if self.por_tamano and self.tam[a] > self.tam[b]:
a, b = b, a # la raíz del árbol menor cuelga de la del mayor
self.padre[a] = b # con por_tamano=False, la de x cuelga siempre de la de y
self.tam[b] += self.tam[a]
return True
def altura(self):
def prof(x):
d = 0
while self.padre[x] != x:
x = self.padre[x]
d += 1
return d
return max(prof(x) for x in range(len(self.padre)))
def aleatoria(n, m, semilla=0):
r = random.Random(semilla)
return [("u", r.randrange(n), r.randrange(n)) if r.random() < 0.5 else ("f", r.randrange(n)) for _ in range(m)]
def cadena(n, repeticiones):
ops = [("u", i, i + 1) for i in range(n - 1)] # con enlace ingenuo, forma una cadena
return ops + [("f", 0)] * repeticiones
def binomial(k):
"""Secuencia de Fischer / Tarjan y van Leeuwen para la compresión sin rango (2^k nodos binomiales + 2^k rondas)."""
n = 2 ** (k + 1)
uf = UnionFind(n, por_tamano=False, compresion="completa")
ops, nivel = [], list(range(2 ** k))
while len(nivel) > 1: # árbol binomial B_k por fusiones de pares
siguiente = []
for i in range(0, len(nivel), 2):
ops.append(("u", nivel[i], nivel[i + 1]))
uf.unir(nivel[i], nivel[i + 1])
siguiente.append(nivel[i + 1])
nivel = siguiente
raiz = nivel[0]
for nuevo in range(2 ** k, n): # raíz nueva encima y búsqueda desde la hoja más profunda
ops.append(("u", raiz, nuevo))
uf.unir(raiz, nuevo)
raiz = nuevo
prof = {}
def d(x):
if x not in prof:
prof[x] = 0 if uf.padre[x] == x else 1 + d(uf.padre[x])
return prof[x]
hoja = max(range(nuevo + 1), key=d)
ops.append(("f", hoja))
uf.buscar(hoja)
return n, ops
def ejecutar(n, ops, **kw):
uf = UnionFind(n, **kw)
for op in ops:
if op[0] == "u":
uf.unir(op[1], op[2])
else:
uf.buscar(op[1])
return uf
CONFIGS = [("ninguna", dict(por_tamano=False, compresion="ninguna")),
("solo tamaño", dict(por_tamano=True, compresion="ninguna")),
("solo compresión", dict(por_tamano=False, compresion="completa")),
("tamaño + compresión", dict(por_tamano=True, compresion="completa")),
("tamaño + mitad", dict(por_tamano=True, compresion="mitad"))]
n_b, ops_b = binomial(8)
escenarios = [("aleatoria", 4096, aleatoria(4096, 8192)),
("cadena y búsquedas", 2048, cadena(2048, 20)),
("binomial (adversaria)", n_b, ops_b)]
for nombre, n, ops in escenarios:
print(f"{nombre}: n = {n}, {len(ops)} operaciones")
for etiqueta, kw in CONFIGS:
uf = ejecutar(n, ops, **kw)
print(f" {etiqueta:22s} punteros/op = {uf.punteros / len(ops):8.2f} búsqueda más cara = {uf.mayor:5d} altura final = {uf.altura()}")In the random sequence, without heuristics mean cost is tens of pointers per operation (with heights of hundreds), and with rank and compression it drops below one (many operations land on nodes already pointing to the root). In the chain the two halves are separate: size only prevents the chain from the start, whereas compression only lets it form and pays for one -pointer search, after which all cost . The binomial sequence separates “compression only” from “size + compression”: the former pays pointers per search each round (mean pointers per operation, three times the latter), and the latter leaves a flat tree (final height ). With the difference would grow logarithmically, but each cell must finish in a few seconds.
Second exercise: Monte Carlo percolation and image component labeling. Here the minimal structure (size plus path splitting) matters, along with comparing its labeling partition with scipy.ndimage.label.
import random
import numpy as np
from scipy import ndimage
class DSU:
"""Versión mínima: unión por tamaño y división de caminos, iterativa."""
def __init__(self, n):
self.p = list(range(n))
self.tam = [1] * n
self.pasos = 0
def buscar(self, x):
p = self.p
while p[x] != x:
p[x], x = p[p[x]], p[x] # cada nodo apunta a su abuelo
self.pasos += 1
return x
def unir(self, x, y):
a, b = self.buscar(x), self.buscar(y)
if a == b:
return False
if self.tam[a] < self.tam[b]:
a, b = b, a
self.p[b] = a
self.tam[a] += self.tam[b]
return True
def percolar(n, rng):
"""Abre celdas al azar hasta que el techo conecta con el suelo. Devuelve (fracción abierta, pasos de puntero por apertura)."""
techo, suelo = n * n, n * n + 1
d = DSU(n * n + 2)
orden = list(range(n * n))
rng.shuffle(orden)
abierta = [False] * (n * n)
for k, c in enumerate(orden, 1):
abierta[c] = True
i, j = divmod(c, n)
if i == 0:
d.unir(c, techo)
if i == n - 1:
d.unir(c, suelo)
for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
a, b = i + di, j + dj
if 0 <= a < n and 0 <= b < n and abierta[a * n + b]:
d.unir(c, a * n + b)
if d.buscar(techo) == d.buscar(suelo):
return k / (n * n), d.pasos / k
return 1.0, d.pasos / (n * n)
rng = random.Random(2024)
for n in (16, 32, 48):
res = [percolar(n, rng) for _ in range(30)]
umbral = np.array([r[0] for r in res])
print(f"n = {n:2d}: umbral medio {umbral.mean():.3f} ± {umbral.std(ddof=1) / np.sqrt(len(umbral)):.3f} pasos por apertura {np.mean([r[1] for r in res]):.2f}")
def etiquetar(imagen):
"""Etiquetado de componentes conexas (4 vecinos) con union-find: una pasada para unir, otra para nombrar."""
h, w = imagen.shape
d = DSU(h * w)
for i in range(h):
for j in range(w):
if imagen[i, j]:
if i > 0 and imagen[i - 1, j]:
d.unir(i * w + j, (i - 1) * w + j)
if j > 0 and imagen[i, j - 1]:
d.unir(i * w + j, i * w + j - 1)
nombres, salida = {}, np.zeros((h, w), dtype=int)
for i in range(h):
for j in range(w):
if imagen[i, j]:
salida[i, j] = nombres.setdefault(d.buscar(i * w + j), len(nombres) + 1)
return salida, len(nombres)
img = np.random.default_rng(5).random((64, 64)) < 0.55
mia, k_mia = etiquetar(img)
ref, k_ref = ndimage.label(img) # estructura por defecto: 4 vecinos
iguales = all(len(set(ref[mia == e])) == 1 for e in range(1, k_mia + 1)) # misma partición, quizá con otros nombres
print(f"componentes: union-find {k_mia}, scipy.ndimage.label {k_ref}, misma partición: {k_mia == k_ref and iguales}")Mean grid threshold is around for all three sizes, compatible with (with grids per size, standard error is between and : this is a statistical estimate, not an exact value), and each opening costs about pointers (counting the percolation query) without growing with . Labeling agrees with SciPy in component count and partition: only label names differ.
Applications
Kruskal and cycle detection
Kruskal’s algorithm visits edges in increasing weight and retains each that does not close a cycle with those already chosen: that is, one joining two distinct components. This is union-find directly: if union(u, v): añadir arista. Cost is sorting, , plus for unions. The same idea detects cycles in an undirected graph: an edge whose endpoints are already in the same set closes a cycle. It does not work for directed graphs: in , , all three nodes end in the same set but there is no directed cycle. Weak connectivity ignores edge direction, which directed cycles require (use depth-first search with colors or topological ordering instead).
Percolation
A grid whose cells open independently with probability percolates if an open-cell path connects top to bottom. There is a sharp threshold: for large , percolation probability changes from to around (Newman and Ziff, 2000, estimated for square-lattice site percolation). To simulate it nothing must be recomputed after each opening: add two virtual nodes, ceiling and floor, linked to every open cell in the first and last rows, and simply ask whether find(techo) == find(suelo). Each opening makes at most four unions with open neighbors.
Tarjan’s offline LCA
The lowest common ancestor of two tree nodes (LCA) has an online solution using the RMQ reduction in the range-query lesson. If queries are known beforehand, there is an offline union-find solution (Tarjan, 1979): traverse the tree depth-first and when node finishes (its whole subtree has been traversed), first answer its queries and then merge its set with its parent’s, marking that parent as ancestro of the resulting set. For query , when finishes and has already finished, LCA is the ancestro of ‘s set at that moment (if is a descendant of , that ancestor is itself; order therefore matters). The invariant is that each set contains an open node (on the traversal stack) and completed nodes whose deepest open ancestor is it, and its ancestro is that open node; if is finished, the LCA of and the node being finished is precisely ‘s deepest open ancestor. You will implement it in the coding exercise.
Offline connectivity with deletions
Union-find cannot delete: a tree cannot be “split” without knowing who hung under whom. But if deletions are known beforehand, time can be reversed.
For deletion-only sequences, start from the final graph (edges never deleted) and process deletions in reverse order: undoing deletion of edge inserts it, and union-find supports insertions. If query answers are saved in a list, read them backwards. Mixed insertions and deletions with arbitrary lifetimes are solved using a segment tree over time and union-find with rollback: union by size without compression, storing which root hung under which on a stack so it can be reverted. Without compression cost per operation is , and the technique gives for updates. Compression cannot be combined with rollback cheaply: it rewrites many pointers, each of which would need logging.
import random
import time
import networkx as nx
def componentes_tras_borrados(n, aristas, borrados):
"""Borrados conocidos de antemano: se procesan en orden inverso, que convierte el borrado en inserción.
Devuelve la lista c, con c[i] = número de componentes tras borrar las i primeras aristas de `borrados`."""
quitadas = set(borrados)
d = DSU(n)
comp = n
for e in aristas:
if e not in quitadas: # el grafo final: lo que nunca se borra
comp -= d.unir(*e)
respuesta = [0] * (len(borrados) + 1)
respuesta[len(borrados)] = comp
for i in range(len(borrados) - 1, -1, -1):
comp -= d.unir(*borrados[i]) # deshacer el borrado i es insertar esa arista
respuesta[i] = comp
return respuesta
def con_networkx(n, aristas, borrados):
"""Referencia: recalcular las componentes desde cero tras cada borrado."""
g = nx.Graph()
g.add_nodes_from(range(n))
g.add_edges_from(aristas)
res = [nx.number_connected_components(g)]
for e in borrados:
g.remove_edge(*e)
res.append(nx.number_connected_components(g))
return res
rng = random.Random(11)
n, m, k = 600, 720, 300
todas = set()
while len(todas) < m:
a, b = rng.sample(range(n), 2)
todas.add((min(a, b), max(a, b)))
aristas = sorted(todas)
borrados = rng.sample(aristas, k) # orden de borrado
t0 = time.perf_counter()
rapida = componentes_tras_borrados(n, aristas, borrados)
t1 = time.perf_counter()
lenta = con_networkx(n, aristas, borrados)
t2 = time.perf_counter()
print(f"mismas respuestas: {rapida == lenta}")
print(f"componentes: al empezar {rapida[0]}, tras borrar {k} aristas {rapida[-1]}")
print(f"tiempo: union-find offline {1000 * (t1 - t0):.1f} ms, recalcular con networkx {1000 * (t2 - t1):.0f} ms")This lab reuses the DSU class from the preceding cell. Both answer lists agree and the reverse method makes one union pass versus complete recomputations: recomputation time grows as and reverse-method time as .
Can it be done online? With deletions arriving without warning, union-find is insufficient. Holm, de Lichtenberg and Thorup (2001) solve it with amortized per update using a hierarchy of spanning forests, and Pătraşcu and Demaine (2006) proved unavoidable in the cell-probe model. This is the difference between a “nearly linear” problem and one with a logarithmic barrier.
With libraries
For a static graph union-find is rarely necessary: SciPy supplies scipy.sparse.csgraph.connected_components (graph traversal in C, linear time when the graph is already fully in memory) and scipy.cluster.hierarchy.linkage (single linkage is the minimum spanning tree). Ready-made structures also exist for the incremental version: scipy.cluster.hierarchy.DisjointSet (union by size and path halving) and networkx.utils.UnionFind (union by size and iterative full compression), both supporting arbitrary hashable elements, not just integers. The lab checks equivalence between Kruskal with union-find and single linkage, and between cutting the dendrogram and stopping Kruskal.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import pdist
rng = np.random.default_rng(3)
pts = np.vstack([rng.normal(c, 0.4, size=(40, 2)) for c in ([0, 0], [4, 0], [2, 3.5])])
n = len(pts)
d = pdist(pts) # distancias en el orden de scipy: (0,1), (0,2), ..., (n-2, n-1)
i, j = np.triu_indices(n, k=1)
orden = np.argsort(d, kind="stable")
# Kruskal: recorrer las aristas por peso creciente y unir si no cierran un ciclo (con la clase DSU de arriba)
dsu, alturas, fusiones = DSU(n), [], 0
for e in orden:
if dsu.unir(int(i[e]), int(j[e])):
alturas.append(d[e])
fusiones += 1
if fusiones == n - 1:
break
Z = linkage(pts, method="single") # el enlace simple es el árbol generador mínimo
print("alturas de fusión de Kruskal = alturas de linkage(single):", np.allclose(alturas, Z[:, 2]))
# cortar el dendrograma a la altura h equivale a parar Kruskal antes de las aristas de peso > h
h = 1.0
dsu2 = DSU(n)
for e in orden:
if d[e] > h:
break
dsu2.unir(int(i[e]), int(j[e]))
mias = len({dsu2.buscar(x) for x in range(n)})
etiquetas = fcluster(Z, t=h, criterion="distance")
print(f"cortando a h = {h}: {mias} clusters con union-find, {len(set(etiquetas))} con fcluster")
# componentes conexas de un grafo disperso con la rutina de scipy (un recorrido del grafo en C)
mask = d <= h
G = coo_matrix((np.ones(mask.sum()), (i[mask], j[mask])), shape=(n, n))
k, lab = connected_components(G, directed=False)
print("scipy.sparse.csgraph.connected_components:", k, "componentes")
# la estructura incremental ya hecha de scipy: DisjointSet (unión por tamaño y reducción a la mitad)
from scipy.cluster.hierarchy import DisjointSet
ds = DisjointSet(range(n))
for e in orden:
if d[e] > h:
break
ds.merge(int(i[e]), int(j[e]))
print("scipy.cluster.hierarchy.DisjointSet:", ds.n_subsets, "conjuntos")Three practical ideas. First, single linkage is Kruskal: dendrogram merge heights are minimum-spanning-tree edge weights in increasing order, and cutting at height means stopping on reaching edges heavier than . Second, static graph components come from connected_components without union-find; union-find’s advantage is incremental updating. Third, for that incremental update DisjointSet agrees with the custom class but adds Python-dictionary overhead per operation; in a critical loop over integers , the well-tested twenty-line list-based version remains the natural choice, and is the only one that can be instrumented or modified (rollback, ancestors, weights).
Common mistakes
Exercises
Step 1 of 4. Which nodes can change rank or size when linking root under root (with )?
Step 1 of 4. After building and placing a new root above the root of , how many pointers does a search from the deepest leaf follow?
union(0,1), union(1,2), ..., union(998,999) with naive linking (the first argument's root hangs below the second's), without union by rank and with full compression. Then perform find(0) searches. Counting one pointer per edge followed by find (including inside union), how many pointers are followed in total?More than one answer may be correct.
def union(x, y): padre[x] = y (without calling find first) and uses path compression in find. What happens with union(3, 5), union(3, 7), find(5) == find(7)?lca_offline(n, padre, consultas): it receives the tree as array padre (padre[raiz] = -1; root can have any label) and a list of pairs (u, v), and returns each pair’s lowest common ancestor in the same order. Use Tarjan’s algorithm: an iterative depth-first traversal (tests include a 20000-node path) and union-find, merging each node with its parent when it finishes. A node counts as its own ancestor: lca(v, v) = v.def lca_offline(n, padre, consultas):
"""LCA de cada par de la lista consultas con el algoritmo offline de Tarjan.
padre[v] es el padre de v y padre[raiz] = -1. Devuelve la lista de ancestros comunes, en el orden de las consultas."""
return [] # tu códigoSummary
- Representation. An array
padre;findclimbs to the root,unionlinks roots. Weighted-union lists already give (each element is relabeled at most times). - Union by rank or size: a node of rank has descendants and height is . Path compression (full, splitting or halving): alone it gives , and binomial sequences force per round.
- Both heuristics: by rank blocks (A, B and C charges), and by Tarjan’s potential, with and up to a tower of 2048 twos. The bound is optimal (Tarjan 1979, Fredman and Saks 1989) and is recovered with Seidel and Sharir’s top-down analysis.
- Applications: Kruskal, percolation (virtual ceiling and floor nodes), image labeling, Tarjan’s offline LCA, offline connectivity with reversed deletions, rollback with union by size without compression.
- Limits: no individual operation is constant, online deletion requires another structure (Holm, de Lichtenberg and Thorup, amortized ), and directed cycles are not a weak-connectivity problem.
Beyond this lesson, the idea of canonicalizing representatives with a tree that flattens as used reappears in unification, SMT solvers’ congruence closure, and single-linkage clustering in the clustering lesson. Analytically, this structure is the best example of a potential that measures nothing physical about state: it is accounting designed for the proof, with Ackermann staircase levels the program never computes. It is an extreme case of asymptotic notation: , but no writable makes it exceed 4.