← All Exercises

Union-Find Components with Path Compression

advancedjavascript~15min

Background

Union-find answers connectivity questions in near-constant amortized time. It powers network clustering, image labeling, and Kruskal's minimum spanning tree.

Problem

Implement DisjointSet for n elements indexed 0 to n-1 with find, union, members, and components. find uses path compression, union uses rank, and union returns false for elements already connected. Process union and query operations, then report the last query's members and the final component count.

Input

A JSON object with n and ops, where each op is a union of two indexes or a query for one index.

Output

A JSON object with members (sorted indexes in the last queried component, or null) and components (final count).

Sample tests

Sample 1

Input: {"n":5,"ops":[{"type":"union","a":0,"b":1},{"type":"union","a":3,"b":4},{"type":"union","a":1,"b":3},{"type":"query","node":0}]}
Expected: {"members":[0,1,3,4],"components":2}

Sample 2

Input: {"n":3,"ops":[{"type":"query","node":2}]}
Expected: {"members":[2],"components":3}

Sample 3

Input: {"n":4,"ops":[{"type":"union","a":0,"b":1},{"type":"union","a":1,"b":0},{"type":"union","a":2,"b":3},{"type":"query","node":1}]}
Expected: {"members":[0,1],"components":2}

Your solution

Learning objective

Practice union-find internals, amortized complexity, and component enumeration.