0
0
DSA Typescriptprogramming

Path Compression in Union Find in DSA Typescript

Choose your learning style9 modes available
Mental Model
Path compression makes finding the group leader faster by flattening the tree structure during searches.
Analogy: Imagine a family tree where each person points to their parent. Path compression is like updating everyone on the path to point directly to the oldest ancestor, so next time you find the ancestor faster.
Before path compression:
1 -> 2 -> 3 -> 4 -> null
After path compression:
1 -> 4
2 -> 4
3 -> 4
4 -> null
Dry Run Walkthrough
Input: Union-Find with elements 1 to 4, unions: union(1,2), union(2,3), union(3,4), then find(1)
Goal: Show how path compression flattens the tree when finding the leader of element 1
Step 1: union(1,2) links 1's leader to 2
1 -> 2 -> null
2 -> null
3 -> null
4 -> null
Why: We connect 1 and 2 so they share the same leader
Step 2: union(2,3) links 2's leader to 3
1 -> 2 -> 3 -> null
2 -> 3 -> null
3 -> null
4 -> null
Why: We connect 2 and 3, extending the chain
Step 3: union(3,4) links 3's leader to 4
1 -> 2 -> 3 -> 4 -> null
2 -> 3 -> 4 -> null
3 -> 4 -> null
4 -> null
Why: We connect 3 and 4, making 4 the leader
Step 4: find(1) traverses from 1 to 4, compressing path
1 -> 4
2 -> 4
3 -> 4
4 -> null
Why: Path compression updates all nodes on path to point directly to leader 4
Result:
1 -> 4
2 -> 4
3 -> 4
4 -> null
Leader of 1 is 4
Annotated Code
DSA Typescript
class UnionFind {
  parent: number[];

  constructor(size: number) {
    this.parent = Array(size + 1).fill(0).map((_, i) => i);
  }

  find(x: number): number {
    if (this.parent[x] !== x) {
      this.parent[x] = this.find(this.parent[x]); // path compression
    }
    return this.parent[x];
  }

  union(a: number, b: number): void {
    const rootA = this.find(a);
    const rootB = this.find(b);
    if (rootA !== rootB) {
      this.parent[rootA] = rootB; // link rootA to rootB
    }
  }
}

// Driver code
const uf = new UnionFind(4);
uf.union(1, 2);
uf.union(2, 3);
uf.union(3, 4);

console.log('Parent array after unions:', uf.parent.slice(1).join(' '));

const leader = uf.find(1);
console.log('Leader of 1 is', leader);
console.log('Parent array after path compression:', uf.parent.slice(1).join(' '));
if (this.parent[x] !== x) {
check if current node is not leader
this.parent[x] = this.find(this.parent[x]); // path compression
recursively find leader and update current node to point directly to leader
return this.parent[x];
return leader of current node
const rootA = this.find(a);
find leader of element a
const rootB = this.find(b);
find leader of element b
if (rootA !== rootB) {
only union if leaders differ
this.parent[rootA] = rootB; // link rootA to rootB
attach rootA's tree under rootB to merge sets
OutputSuccess
Parent array after unions: 2 3 4 4 Leader of 1 is 4 Parent array after path compression: 4 4 4 4
Complexity Analysis
Time: O(α(n)) per find/union operation because path compression flattens trees making future finds almost constant time
Space: O(n) for storing parent array for n elements
vs Alternative: Without path compression, find can be O(n) in worst case due to tall trees; path compression reduces this to nearly O(1)
Edge Cases
Finding leader of an element that is its own leader
Returns the element itself immediately without recursion
DSA Typescript
if (this.parent[x] !== x) {
Union of two elements already in the same set
No change to parent array as leaders are equal
DSA Typescript
if (rootA !== rootB) {
Union and find on single element set
Find returns element itself; union links sets correctly
DSA Typescript
if (this.parent[x] !== x) {
When to Use This Pattern
When you see problems about grouping elements and quickly checking if two elements belong to the same group, use Union Find with path compression to speed up repeated queries.
Common Mistakes
Mistake: Not updating the parent during find, missing path compression
Fix: Assign parent[x] = find(parent[x]) to flatten the tree
Mistake: Linking parents incorrectly in union causing cycles
Fix: Always link root of one set to root of another after finding leaders
Summary
Path compression speeds up finding the leader by making nodes point directly to the leader.
Use it when you need fast repeated union and find operations on disjoint sets.
The key insight is flattening the tree during find to make future finds faster.