Disjoint Sets Continued
Week 12, Tuesday
March 24, 2026
Announcements
- PA3 due Week 12
- PEX5 this week!
Example: Partition of Elements into Disjoint Sets
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
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
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.