Disjoint Set Union (Union-Find) - Problem
Implement a Disjoint Set Union (DSU) data structure with union by rank and path compression optimizations. Use it to solve a dynamic connectivity problem.
Given a series of operations to connect nodes and check if two nodes are connected, efficiently determine the connectivity status after each query.
Your task is to implement:
union(x, y): Connect nodes x and yfind(x): Find the root parent of node x with path compressionconnected(x, y): Check if nodes x and y are in the same component
Process a list of operations and return the results of all connectivity queries.
Input & Output
Example 1 — Basic Union and Connected Operations
$
Input:
n = 4, operations = [["union",0,1], ["connected",0,1], ["connected",0,2]]
›
Output:
[true, false]
💡 Note:
After union(0,1), nodes 0 and 1 are connected. Query connected(0,1) returns true. Query connected(0,2) returns false since 2 is not connected to 0.
Example 2 — Multiple Components
$
Input:
n = 5, operations = [["union",0,1], ["union",2,3], ["connected",1,3], ["union",1,2], ["connected",0,3]]
›
Output:
[false, true]
💡 Note:
Initially 0-1 and 2-3 are separate components. connected(1,3) is false. After union(1,2), all nodes 0,1,2,3 are connected, so connected(0,3) is true.
Example 3 — Self Connection
$
Input:
n = 3, operations = [["connected",0,0], ["union",0,1], ["connected",1,1]]
›
Output:
[true, true]
💡 Note:
Any node is always connected to itself. Both connected(0,0) and connected(1,1) return true.
Constraints
- 1 ≤ n ≤ 104
- 1 ≤ operations.length ≤ 104
- operations[i] is either ["union", x, y] or ["connected", x, y]
- 0 ≤ x, y < n
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code