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 y
  • find(x): Find the root parent of node x with path compression
  • connected(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
INPUT OPERATIONSDSU ALGORITHMRESULTSn = 4 nodesoperations = [["union", 0, 1],["connected", 0, 1]]0123Union connects 0↔1Check if 0 connected to 11Initialize parent array2Union by rank3Path compression4Check connectivityparent = [1, 1, 2, 3]rank = [0, 1, 0, 0]find(0) = find(1) = 1 ✓Query Results:trueconnected(0,1)Output: [true]Nodes 0 and 1 are inthe same componentKey Insight:Union by rank and path compression make DSU operations nearly O(1),enabling efficient dynamic connectivity queries on large datasets.TutorialsPoint - Disjoint Set Union (Union-Find) | Optimized DSU
Asked in
Google 45 Facebook 38 Amazon 35 Microsoft 32
78.0K Views
Medium-High Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen