{"post":{"slug":"what-is-union-find-2026","title":"What Is Union-Find? 2026 Guide","excerpt":"Union-find is a data structure built for one question: are these two things in the same group. Here is how it answers that almost instantly, and why the naive version is nowhere near fast enough.","category":"code","date":"July 24, 2026","author":"ByteLedger Team","content":"<span class=\"dropcap\">U</span>nion-find — also called disjoint set union, or DSU — is a data structure built to answer one question fast: are these two elements in the same group. It supports exactly two operations, find and union, and the design effort behind it goes into making both run in close to constant time, even across millions of merges.\n\n## What changed in 2026\n\n- **It stayed exactly the same, and that is the point.** Union-find with path compression and union by rank has been near-optimal since the 1980s; nothing about the core algorithm needed to change. What shifted is where it shows up — more graph libraries expose it as a first-class utility instead of something you hand-roll.\n- **It became a common building block in dedupe and entity-resolution pipelines.** Merging records that reference the same underlying entity across noisy datasets is a union-find problem in disguise, and more data tooling names it as such now.\n- **Interview and systems-design emphasis picked back up.** As graph and dependency reasoning became more visible in day-to-day engineering work, union-find re-entered technical interviews alongside topological sort as a \"can you reason about connectivity\" check.\n\n## The two operations\n\n- **find(x)** — returns a representative (or \"root\") for the group x belongs to. Two elements are in the same group exactly when find returns the same root for both.\n- **union(x, y)** — merges the groups containing x and y into one group.\n\nThat is the entire interface. No iteration over members, no ordering, no removal. If your problem needs more than \"same group or not,\" union-find alone is not enough.\n\n## Why the naive version is not good enough\n\nThe simplest implementation stores a parent pointer per element and walks up to the root on every find. Left alone, repeated unions can build a long chain, turning what should be a fast lookup into an O(n) walk. Two small additions fix this completely:\n\n- **Path compression** — while walking up during find, point every node on the path directly at the root. Future finds on those nodes become instant.\n- **Union by rank or size** — when merging two groups, always attach the smaller (or shallower) tree under the root of the larger one, instead of picking arbitrarily.\n\n```python\nclass UnionFind:\n    def __init__(self, n):\n        self.parent = list(range(n))\n        self.rank = [0] * n\n\n    def find(self, x):\n        if self.parent[x] != x:\n            self.parent[x] = self.find(self.parent[x])  # path compression\n        return self.parent[x]\n\n    def union(self, x, y):\n        rx, ry = self.find(x), self.find(y)\n        if rx == ry:\n            return\n        if self.rank[rx] < self.rank[ry]:\n            rx, ry = ry, rx\n        self.parent[ry] = rx\n        if self.rank[rx] == self.rank[ry]:\n            self.rank[rx] += 1\n```\n\n## Naive vs optimized performance\n\n| Version | find / union cost | Notes |\n| --- | --- | --- |\n| Parent pointers only | Up to O(n) per operation | Can degrade to a linked list |\n| + Union by rank only | O(log n) per operation | Keeps trees shallow |\n| + Path compression only | Close to O(log n) amortized | Flattens paths over time |\n| Both combined | Amortized inverse-Ackermann — effectively constant | Standard production implementation |\n\nThe combined version is fast enough that, for any input size that fits in memory, you can treat each operation as roughly constant time in practice.\n\n## Where union-find actually gets used\n\n- **Kruskal minimum spanning tree.** Sort edges by weight, and add each edge only if its two endpoints are not already unioned — this is exactly what prevents a cycle from forming.\n- **Cycle detection in undirected graphs.** If union(x, y) is called and find(x) already equals find(y), that edge would create a cycle.\n- **Connected components.** Union every pair of directly connected nodes, then group elements by their final root.\n- **Image processing.** Labeling connected regions of pixels is a grid version of the same connectivity problem.\n\n## Common mistakes\n\n**Forgetting path compression, union by rank, or both.** Either alone is fine; skipping both causes the classic worst-case slowdown people warn about.\n\n**Expecting union-find to support \"un-union.\"** It is a one-directional merge structure. If you need to split groups back apart, you need a different structure or need to rebuild.\n\n**Trying to list all members of a group cheaply.** Union-find does not track membership lists by default; you would need to maintain that separately if your problem requires it.\n\n## FAQ\n\n**Is union-find the same as a graph?**\nNo. It represents a partition into disjoint groups, not edges and paths between individual nodes, though it is commonly used alongside graph algorithms.\n\n**What does the inverse-Ackermann time complexity actually mean?**\nIt grows so slowly that for any input size you could realistically store in memory, it is indistinguishable from a small constant. It is not literally O(1), but it behaves like it in practice.\n\n**Can union-find detect cycles in a directed graph?**\nNot directly — it is built for undirected connectivity. Directed-graph cycle detection needs a different approach, such as the DFS coloring method used to validate a [directed acyclic graph](/blog/what-is-a-directed-acyclic-graph-2026).\n\n**Do I need union by rank if I already have path compression?**\nBoth together give the best guaranteed bound. Path compression alone is very fast in practice, but combining both is the standard, safest choice.\n\n## Where to go next\n\n- [What is a directed acyclic graph in 2026](/blog/what-is-a-directed-acyclic-graph-2026)\n- [What is topological sort in 2026](/blog/what-is-topological-sort-2026)\n- [What is a segment tree in 2026](/blog/what-is-a-segment-tree-2026)","hue":290,"metaTitle":"Union-Find Explained 2026","metaDescription":"What is union-find in 2026? A practical guide to the disjoint set union structure, path compression, union by rank, and where it gets used in code.","keywords":["union find 2026","disjoint set union","union find algorithm","path compression union find","union by rank","kruskal minimum spanning tree","union find python","connected components algorithm","disjoint set data structure"],"tldr":["**It tracks groups, not order** — union-find answers whether two elements belong to the same set, fast, and does not try to do more than that.","**Two operations carry the whole structure** — find (which group is this element in) and union (merge two groups) are the entire interface.","**Path compression and union by rank make it nearly constant time** — without both optimizations it can degrade toward a plain linked list.","**It is the backbone of Kruskal minimum spanning tree** — plus cycle detection in undirected graphs, connectivity checks, and image region labeling.","**Skip:** reaching for union-find when you need to cheaply list every member of a group — it answers \"same group or not\" fast, not \"who else is in this group.\""],"readTime":"4 min read","wordCount":902},"related":[{"slug":"what-is-a-segment-tree-2026","title":"What Is a Segment Tree? 2026 Guide","excerpt":"A segment tree answers range questions over an array — sum, min, max — in logarithmic time, and lets you update an element without rebuilding anything. Here is how it is built and when it is overkill.","category":"code","date":"July 20, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":280},{"slug":"what-is-a-graph-data-structure-2026","title":"What Is a Graph Data Structure? 2026 Guide","excerpt":"A graph is nodes plus edges, with no hierarchy required, unlike a tree. This 2026 guide covers directed vs undirected, adjacency lists vs matrices, and how graphs get traversed.","category":"code","date":"July 18, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":240},{"slug":"what-is-a-directed-acyclic-graph-2026","title":"What Is a Directed Acyclic Graph? 2026 Guide","excerpt":"A directed acyclic graph, or DAG, is a graph whose edges point one way and never loop back on themselves. Here is what that one rule enables and where DAGs quietly run your software.","category":"code","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":240}],"sameCategory":[{"slug":"bazel-build-explained-2026","title":"Bazel Explained: What Hermetic Builds Actually Cost","excerpt":"Bazel delivers reproducible, precisely cached builds and demands that you describe everything. Here is what you get, what it costs, and who should say no.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":145},{"slug":"graphql-federation-2026","title":"GraphQL Federation: One Graph, Many Teams","excerpt":"Federation composes independently-owned subgraphs into a single API. Here is what it solves, the operational cost it adds, and when a simpler gateway is enough.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":300},{"slug":"hermetic-builds-explained-2026","title":"Hermetic Builds Explained: Same Inputs, Same Output","excerpt":"A hermetic build depends only on declared inputs. Here is what that property gives you, the common leaks that break it, and how to move toward it incrementally.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":130},{"slug":"monorepo-tooling-compared-2026","title":"Monorepo Tooling Compared: What You Actually Need","excerpt":"Monorepo tools solve task orchestration and caching, not repository layout. Here is what each tier provides and how to tell when you have outgrown the simple option.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":150}],"newer":{"slug":"what-is-two-phase-commit-2026","title":"What Is Two-Phase Commit in 2026: The Protocol Explained","excerpt":"Two-phase commit is the classic protocol for making a transaction atomic across multiple nodes. Here is the 2026 guide to how prepare and commit phases work, why it can block, and when a saga is the better call.","category":"code","date":"July 24, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":290},"older":{"slug":"what-is-usb-power-delivery-wattage-2026","title":"What is USB power delivery wattage in 2026: a plain explainer","excerpt":"USB Power Delivery wattage determines how fast a device charges and whether one charger can safely cover a laptop, phone, and tablet. Here is how the numbers actually work in 2026.","category":"tech","date":"July 24, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":280}}