← All Exercises

Union-Find with Size Tracking

intermediatejavascript~15min

Background

Union-find answers connectivity queries in near-constant amortized time. Component-size tracking is how image labeling and network partition monitors summarize merge progress.

Problem

Implement union-find over n elements with union by size and path compression. Process a list of union operations; after each one, record the size of the largest component. Output that running maximum list.

Input

A JSON object {"n": number, "ops": [{"type":"union","a":number,"b":number}]} with indexes in range.

Output

A JSON object {"maxSizes": number[]} with one entry per operation.

Sample tests

Sample 1

Input: {"n":6,"ops":[{"type":"union","a":0,"b":1},{"type":"union","a":2,"b":3},{"type":"union","a":4,"b":5},{"type":"union","a":1,"b":3},{"type":"union","a":0,"b":5}]}
Expected: {"maxSizes":[2,2,2,4,6]}

Sample 2

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

Your solution

Learning objective

Reinforce union by size, path compression, and component statistics.