What is the primary purpose of a Disjoint Set (Union-Find) data structure?
Think about grouping elements and checking their group membership efficiently.
The Disjoint Set data structure is designed to keep track of elements partitioned into disjoint sets and supports two main operations: finding which set an element belongs to and uniting two sets. It is not used for sorting, key-value storage, or priority queues.
What is the amortized time complexity of the find and union operations in a Disjoint Set with path compression and union by rank/size?
The inverse Ackermann function grows extremely slowly and is practically constant for all reasonable input sizes.
With path compression and union by rank or size, both find and union operations run in nearly constant time, specifically O(α(n)), where α(n) is the inverse Ackermann function, which grows very slowly and can be considered almost constant for all practical input sizes.
Given a Disjoint Set with elements {1, 2, 3, 4, 5} initially all separate, what is the number of distinct sets after performing these operations in order?
union(1, 2)
union(3, 4)
union(2, 3)
union(5, 1)
Track how sets merge step-by-step.
Initially, there are 5 sets: {1}, {2}, {3}, {4}, {5}.
After union(1, 2): {1,2}, {3}, {4}, {5}
After union(3, 4): {1,2}, {3,4}, {5}
After union(2, 3): {1,2,3,4}, {5}
After union(5, 1): {1,2,3,4,5}
Only one set remains.
Which statement correctly describes the difference between union by rank and union by size in Disjoint Set implementations?
Consider what 'rank' and 'size' represent in the context of trees.
Union by rank uses the height (or an upper bound on height) of the tree to decide which root becomes the parent, attaching the shorter tree under the taller one. Union by size uses the number of nodes in the tree to decide, attaching the smaller tree under the larger one. They are similar but use different criteria.
Consider an undirected graph with edges added one by one. How can a Disjoint Set be used to detect if adding a new edge creates a cycle?
Think about what it means if two vertices are already connected before adding an edge.
If the two vertices of the new edge are already in the same set, it means they are connected by some path. Adding the edge would create a cycle. If they are in different sets, the edge connects two separate components and does not form a cycle.