{"id":294,"date":"2026-11-13T12:37:13","date_gmt":"2026-11-13T04:37:13","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-union-find-almost-flattens-a-disjoint-set-forest\/"},"modified":"2026-11-13T21:58:44","modified_gmt":"2026-11-13T13:58:44","slug":"how-union-find-almost-flattens-a-disjoint-set-forest","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-union-find-almost-flattens-a-disjoint-set-forest\/","title":{"rendered":"How union-find almost flattens a disjoint-set forest"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Union-find<\/strong> maintains a partition of elements under union and under &#8220;are these two in the same set.&#8221; Each set is a tree of parent pointers. <strong>Union by rank<\/strong> attaches the shorter tree under the taller one, and <strong>path compression<\/strong> points every node on a lookup path at the root. Together, m operations on n elements cost <strong>O(m \u03b1(n))<\/strong> time, where <strong>\u03b1<\/strong> is the inverse Ackermann function and is at most 4 for every practical n. Either optimization alone is only logarithmic.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Kruskal&#8217;s algorithm asks, over and over, whether two endpoints already lie in the same grown component, and if they do not, it merges those components. A linear scan of labels would make that test the slow part of the sort. A parent pointer turns each set into a tree whose root is the set&#8217;s name. The merge is a parent assignment. The test is two root lookups.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Without a balancing rule the tree can become a chain and each lookup is \u0398(n). The two classical repairs are different: one limits height when trees are linked, and the other flattens a path the next time it is walked.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Union by rank gives trees of height O(log n) and a cost of O(log n) per operation. Path compression alone, with a naive link, also reaches O(log n) amortized in the usual analysis of compression without rank, and the combination is the inverse-Ackermann bound. The bound is amortized. One unlucky operation can still walk a long path, after which that path is flat.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Union by size, which hangs the smaller tree under the larger, has the same logarithmic height bound as rank. Rank is an upper bound on height and does not have to be maintained as an exact size. Path compression must not be mixed with a height field that is treated as exact, because compression changes heights and rank does not claim to track them afterward. The structure does not support undo, split, or &#8220;list the members&#8221; in the same bound. Those are different data structures.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set parent[x] = x and rank[x] = 0 for each element.<\/li>\n<li>Find(x) returns parent[x] if x is a root. Otherwise it sets parent[x] = Find(parent[x]) and returns that root. That assignment is path compression.<\/li>\n<li>Same(a, b) compares Find(a) with Find(b).<\/li>\n<li>Union(a, b) finds both roots. If they differ, the root of smaller rank becomes a child of the root of larger rank. Equal ranks pick either root as parent and increment that parent&#8217;s rank.<\/li>\n<li>A successful union returns the new root if the caller is Kruskal and only needs the merge, not the element list.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The inverse-Ackermann bound includes both rank and compression. Quoting it for a parent pointer with neither optimization describes a chain. The structure answers connectivity in a growing partition. It does not store the minimum edge between components unless an extra value is kept at the root, and it does not answer dynamic connectivity after deletions.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when one of the two optimizations is omitted from the bound<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Quote O(m \u03b1(n)) for union by rank without compression<\/td>\n<td>The cost per operation is then \u0398(log n) in the worst case. \u03b1 appears only with both improvements.<\/td>\n<\/tr>\n<tr>\n<td>Compress paths and also decrement ranks as if they were heights<\/td>\n<td>Rank is not exact height after compression. Changing it breaks the link rule that keeps the potential in the proof.<\/td>\n<\/tr>\n<tr>\n<td>Attach an arbitrary root under the other with no rank or size<\/td>\n<td>Adversarial unions build a chain. Each find walks \u0398(n) parents.<\/td>\n<\/tr>\n<tr>\n<td>Use the structure to delete an edge from a spanning tree<\/td>\n<td>Union has no inverse. Dynamic connectivity with deletions needs a different algorithm, such as a link-cut tree for forests.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">The classical client is Kruskal. Any other incremental connectivity problem on an undirected graph, including connected components of a static graph if one prefers this over DFS, uses the same two operations. Offline lowest common ancestors via Tarjan also union subtrees during a depth-first search.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script union by rank and compress paths. After linking 0-1, 2-3, and 1-2, index 0 and index 3 are one set and index 4 is another. Both print <code>1 0<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">for ((i=0; i&lt;5; i++)); do parent[i]=$i; rank[i]=0; done\nfind() {\n  local x=$1\n  while (( parent[x] != x )); do\n    parent[x]=${parent[parent[x]]}\n    x=${parent[x]}\n  done\n  echo &quot;$x&quot;\n}\nunion() {\n  local a b\n  a=$(find &quot;$1&quot;); b=$(find &quot;$2&quot;)\n  if (( a == b )); then return; fi\n  if (( rank[a] &lt; rank[b] )); then local t=$a; a=$b; b=$t; fi\n  parent[b]=$a\n  if (( rank[a] == rank[b] )); then rank[a]=$((rank[a]+1)); fi\n}\nunion 0 1\nunion 2 3\nunion 1 2\nfa=$(find 0); fb=$(find 3); fc=$(find 4)\nif (( fa == fb )); then s1=1; else s1=0; fi\nif (( fa == fc )); then s2=1; else s2=0; fi\necho &quot;$s1 $s2&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">parent = list(range(5))\nrank = [0] * 5\n\ndef find(x):\n    while parent[x] != x:\n        parent[x] = parent[parent[x]]\n        x = parent[x]\n    return x\n\ndef union(a, b):\n    a, b = find(a), find(b)\n    if a == b:\n        return\n    if rank[a] &lt; rank[b]:\n        a, b = b, a\n    parent[b] = a\n    if rank[a] == rank[b]:\n        rank[a] += 1\n\nunion(0, 1)\nunion(2, 3)\nunion(1, 2)\nprint(int(find(0) == find(3)), int(find(0) == find(4)))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Union-find is the disjoint-set structure inside Kruskal&#8217;s algorithm and inside connected-component labeling of an image. Network connectivity and equivalence classes in a compiler use the same parent array. A breadth-first search labels one component; the forest labels all of them.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop union-find when the graph is static and a DFS or BFS component labeling is simpler. Keep it when edges arrive in a stream, when unions are interleaved with queries, or when Kruskal needs the cycle test. Implement both union by rank and path compression if the inverse-Ackermann bound is the one you are relying on.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for union-find returns the pair of optimizations that the inverse-Ackermann bound actually requires. <strong>Union-find with union by rank and path compression answers m connectivity operations on n elements in O(m \u03b1(n)) time, and either optimization by itself is only logarithmic.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Union-find maintains a partition of elements under union and under &#8220;are these two in the same set.&#8221; Each set is a tree of parent pointers. Union by rank attaches the shorter tree under the taller one, and path compression points every node on a lookup path at&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-294","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=294"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/294\/revisions"}],"predecessor-version":[{"id":693,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/294\/revisions\/693"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}