Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Developer docs
Union-find
Union-findReference implementationStep-by-step guideOfficial docs and resourcesDiscussionsComments

Other algorithms

Algorithm basics5
Complexity analysisSortingSearchingBasic data structuresTrees and heaps
Core algorithms6
Graph traversalShortest paths & minimum spanning treesDynamic programmingGreedy algorithmsDivide and conquerBacktracking
Advanced algorithms4
String algorithmsMath and number theoryBit manipulationSegment trees
Practical algorithms4
Coding interview strategyLRU cacheRate limitingConsistent hashing

Algorithm

Union-find

Union-find (disjoint set union) keeps elements in non-overlapping groups and can merge groups or check whether two elements share one in nearly constant time.

Start the guideDiscussions

Union-find, also called the disjoint-set data structure, keeps a collection of elements split into non-overlapping sets. It offers just two operations: find returns the representative of the set an element belongs to, and union merges the sets of two elements. Each set is stored as a tree of parent pointers, and the root of the tree is the set's representative.

When connections only ever get added and you keep asking "are these two connected?", union-find is far faster than searching the graph each time. With path compression and union by rank or size together, the amortized cost per operation drops to the inverse Ackermann function α(n), which never exceeds 4 for any realistic input. It is the standard tool behind Kruskal's minimum spanning tree, cycle detection, connected components and grouping problems such as merging accounts, and it is a frequent coding interview topic.

Start by implementing find and union over a single parent array, and trace by hand how a tree degrades into a chain without optimizations. Then add union by size and path compression one at a time and watch how tree depth changes. Finally, solve connected-component, cycle-detection and Kruskal problems to get used to relying on union's return value.

On this page

  1. Highlights
  2. Where it is used
  3. Reference implementation
  4. Step-by-step guide
  5. Official docs and resources
  6. Discussions
  7. Comments

Highlights

find and union

find follows parent links up to the root (the representative), and union hangs one root under the other to merge two sets.

Path compression

find re-attaches the nodes it visits directly to the root, flattening the tree so later calls are faster.

Union by rank or size

Hanging the smaller tree under the larger keeps every tree's height at most log n.

Nearly constant time

With both optimizations, m operations take O(m α(n)) time, and the inverse Ackermann function α(n) is at most 4 in practice.

Where it is used

  • Tracking connected components in a graph
  • Kruskal's minimum spanning tree
  • Cycle detection in undirected graphs
  • Grouping accounts and records by shared keys

Reference implementation

The DSU class stores the sets in two arrays, parent and size. find walks up the parent links and uses path halving, linking each node to its grandparent, to keep trees flat. union hangs the smaller set under the larger one and returns False when both elements are already in the same set. The example merges six elements into three groups, then prints membership checks and the number of sets.

union_find.py

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True


dsu = DSU(6)
for a, b in [(0, 1), (1, 2), (3, 4)]:
    dsu.union(a, b)
print(dsu.find(2) == dsu.find(0))  # True
print(dsu.find(4) == dsu.find(5))  # False
print(len({dsu.find(x) for x in range(6)}))  # 3
python union_find.py

Step-by-step guide

Six chapters that take you from installation to the core ideas of Union-find.

  1. Concepts: Disjoint Sets and Union-Find
  2. How It Works: Tracing find and union
  3. Implementation: Building a DSU Class
  4. Complexity: Inverse Ackermann in Plain Words
  5. Practice Problems
  6. Real-World Use and Pitfalls

Official docs and resources

  • Officialscipy.cluster.hierarchy.DisjointSet
  • OfficialBoost Disjoint Sets
  • LearnDisjoint Set Union
  • LearnAlgorithms, 4th Edition: Case Study: Union-Find
  • LearnVisuAlgo: Union-Find Disjoint Sets
  • ReferenceDisjoint-set data structure
  • ReferenceKruskal's algorithm
  • ReferenceAckermann function

Discussions

Start a discussion

Ask questions, share experience and trade opinions about Union-find.

No discussions yet. Start the first one.

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.