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

Union-find docs
Union-find
Concepts: Disjoint Sets and Union-FindHow It Works: Tracing find and unionImplementation: Building a DSU ClassComplexity: Inverse Ackermann in Plain WordsPractice ProblemsReal-World Use and Pitfalls
Discussions

Union-find guide · 2/6

How It Works: Tracing find and union

This chapter follows a small example with eight elements (0 to 7) and shows how the parent array changes. First we see how trees degrade without optimizations, then how union by size and path compression fix the problem.

Initial state

Every element starts in its own set, so each one is its own parent. All sizes are 1.

Element01234567
parent01234567
size11111111

The problem with unoptimized merging

Suppose union always hangs the second root under the first. Calling union(1, 0), union(2, 1) and union(3, 2) puts 0 under 1, 1 under 2 and 2 under 3, producing a chain 0 → 1 → 2 → 3. Now find(0) has to climb three links to reach the root 3. With n elements, a single find can cost O(n) in the worst case.

parent = list(range(8))

def find(x):
    steps = 0
    while parent[x] != x:
        x = parent[x]
        steps += 1
    return x, steps

def naive_union(a, b):
    ra, _ = find(a)
    rb, _ = find(b)
    if ra != rb:
        parent[rb] = ra

for i in range(1, 4):
    naive_union(i, i - 1)   # 0 → 1 → 2 → 3
print(find(0))  # (3, 3): three steps to root 3

Union by size

The fix is to hang the smaller tree under the larger one. Then whenever an element's depth grows by one, the set it belongs to at least doubles in size. A set can never exceed n elements, so no depth can exceed log2 n. Union by rank, which compares an upper bound on height instead of the size, gives the same guarantee.

Let us run the following sequence on the same eight elements, merging by size. Each union first calls find on both arguments to get their roots.

StepOperationRoots comparedResult
1union(0, 1)size 1 vs 1, ties keep the first rootparent[1] = 0, size[0] = 2
2union(2, 3)size 1 vs 1parent[3] = 2, size[2] = 2
3union(1, 3)root 0 (size 2) vs root 2 (size 2)parent[2] = 0, size[0] = 4
4union(4, 5)size 1 vs 1parent[5] = 4, size[4] = 2
5union(6, 4)root 6 (size 1) vs root 4 (size 2)parent[6] = 4, size[4] = 3
6union(7, 1)root 7 (size 1) vs root 0 (size 4)parent[7] = 0, size[0] = 5

After step 6 there are two sets, {0, 1, 2, 3, 7} and {4, 5, 6}. The path from element 3 is 3 → 2 → 0, length 2, well within the maximum depth of 3 that eight elements allow.

Path compression

Calling find(3) walks 3 → 2 → 0 and discovers the root 0. Path compression then points every node on that path directly at the root. The next find(3) needs only one hop.

def find(x):
    root = x
    while parent[root] != root:      # pass 1: locate the root
        root = parent[root]
    while parent[x] != root:         # pass 2: point visited nodes at the root
        parent[x], x = root, parent[x]
    return root

Compression happens automatically inside find, so callers never have to think about it. The more often the same elements are queried, the shorter their paths become and the bigger the payoff.

A popular one-pass variant is path halving: while walking up, link each node to its grandparent. The code is shorter and the performance guarantee is the same.

def find_halving(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]  # skip to the grandparent
        x = parent[x]
    return x

Before and after compression

Element01234567
parent before find(3)00024440
parent after find(3)00004440

parent[3] changed from 2 to 0. Compression only flattens the shape of a tree; it never changes which set an element belongs to. Sizes only matter at roots, so they need no update during compression.

Summary

Without optimizations, union-find trees can degrade into long chains. Union by size or rank, which hangs the smaller tree under the larger, bounds tree height by log n, and path compression or path halving flattens trees on every find. The two techniques are independent and work best together.

Questions about this chapter?
Previous chapterConcepts: Disjoint Sets and Union-FindNext chapterImplementation: Building a DSU Class

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.