Question Bank

Union-Find Warm-Up

Difficulty: Medium

Disjoint Set Union with path compression and union by rank. Drills cover find, union, connected-component counts, and Kruskal usage.

Question Bank
/

Union-Find Warm-Up

Union-Find Warm-Up

Disjoint Set Union with path compression and union by rank. Drills cover find, union, connected-component counts, and Kruskal usage.

Question Bank
Medium
JavaScript
4 questions
union-find
union-by-rank
data-structures
quiz

1,097 views

13

Implement find with path compression and union by rank for a DSU over n elements.

Examples

Example 1:

Input: new DSU(4); union(0, 1); union(0, 2); find(2); then union(2, 1)
Output: find(2) returns 0; the final union returns false
Explanation: After the first two unions, {0, 1, 2} share root 0. find(2) compresses the path to 0. The fourth call sees that roots already match (0 == 0) and returns false. Amortized inverse-Ackermann per op.