Disjoint Sets Continued

Week 12, Tuesday

March 24, 2026

Announcements

  • PA3 due Week 12
  • PEX5 this week!

Example: Partition of Elements into Disjoint Sets

2 5 9 7 0 1 4 8 6 3
5 9 2 7 4 0 8 1 3 6 0 1 2 3 4 5 6 7 8 9 4 8 5 6 -1 -1 -1 -1 4 5

UpTree Implementation

def find(self, i):
    if self.s[i] < 0:
        return i
    else:
        return self.find(self.s[i])


Running time depends on ___________.

Worst case? ___________

What’s an ideal tree? ___________


def union(self, root1, root2):
    self.s[root2] = root1

Smart Unions

7 6 8 9 0 1 2 3 4 10 5 11 Union by ____________: 0 6 1 6 2 6 3 8 4 5 10 6 7 7 8 7 9 7 10 4 11 5 Keeps overall height of tree as small as possible. Union by ____________: 0 6 1 6 2 6 3 8 4 5 10 6 7 7 8 7 9 7 10 4 11 5 Increases distance to root for fewest nodes.

Both of these schemes for Union guarantee the height of the tree is ________.

Smart Unions: Implementation

def find(self, i):
    if self.s[i] < 0:
        return i
    else:
        return self.find(self.s[i])


def union_by_size(self, root1, root2):
    new_size = self.s[root1] + self.s[root2]
    if self.s[root1] <= self.s[root2]:   # root1 is bigger (more negative)
        self.s[root2] = root1
        self.s[root1] = new_size
    else:
        self.s[root1] = root2
        self.s[root2] = new_size

Summary

UpTree implementation of ADT Disjoint Sets with smart Union gives:

  • Find: \(O(\log n)\)
  • Union: \(O(1)\)

 

Can we do better?

Path Compression

10 9 11 1 7 2 8 3 4 5 6

Analysis

Something we’ll need — Iterated log:

\[\log^* (n) = \begin{cases} 0 & \text{if } n \leq 1 \\ 1 + \log^*(\log n) & \text{if } n > 1 \end{cases}\]

Example: \(\log^* (2^{65536})\)

Relevant result: In an upTree implementation of Disjoint Sets using smart union and find with path compression…

any sequence of \(m\) union and find operations results in worst case running time of \(O(\_\_\_\_\_\_\_\_\_\_)\), where \(n\) is the number of items.

http://research.cs.vt.edu/AVresearch/UF/

Summary

UpTree implementation of ADT Disjoint Sets with smart Union gives:

  • Find = O(log n)
  • Union = O(1)

 

If we add path compression we achieve nearly constant time for both operations.