Skip to content

Dsa Graph Union Find

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix Union. We cover key concepts, practical examples, and best practices.

Fix union-find / dsu errors when path compression missing or union direction inconsistent.

Quick Fix

Wrong

class DSU:
    def find(self,x):
        if self.p[x]!=x: return self.find(self.p[x])
        return x
    def union(self,x,y):
        self.p[self.find(x)]=self.find(y)

No path compression. O(n) find. Tree height grows unbounded.

class DSU:
    def __init__(self,n):
        self.p=list(range(n)); self.r=[0]*n
    def find(self,x):
        if self.p[x]!=x: self.p[x]=self.find(self.p[x])
        return self.p[x]
    def union(self,x,y):
        rx,ry=self.find(x),self.find(y)
        if rx==ry: return False
        if self.r[rx]<self.r[ry]: self.p[rx]=ry
        elif self.r[rx]>self.r[ry]: self.p[ry]=rx
        else: self.p[ry]=rx; self.r[rx]+=1
        return True
union(0,1),union(1,2),find(0)==find(2) -> True. Nearly O(1) amortized.

Prevention

Always use path compression in find. Use union by rank/size for balanced trees.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is Union-Find?

Data structure tracking elements partitioned into disjoint sets. Union and find operations.

Path compression?

During find, make each visited node point directly to root. Flattens tree.

Union by rank?

Attach smaller tree under larger tree. Keeps height O(log n).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro