Problem Description
You are given an integer n and an object categoryHandler of class CategoryHandler. There are n elements (numbered 0 to n - 1) where each element belongs to a category. Using the provided function haveSameCategory(a, b) from categoryHandler, determine the number of unique categories among the elements.
Key Insights
- The only way to compare two elements' categories is via the function haveSameCategory.
- A straightforward approach is to group elements together using pairwise comparisons.
- Using a Union-Find (disjoint-set) data structure helps in efficiently grouping elements that belong to the same category.
- Given n is small (n <= 100), an O(n^2) solution is acceptable.
Space and Time Complexity
Time Complexity: O(n^2) – Each pair of elements may be compared in the worst case. Space Complexity: O(n) – To store the union-find parent (and optionally rank) arrays.
Solution
We use the Union-Find (disjoint-set) data structure to solve the problem. Initially, each element is its own set. We then iterate over every pair of elements (i, j). If categoryHandler.haveSameCategory(i, j) returns true, we union their sets. After processing all possible pairs, the number of unique categories is equal to the number of unique representative parents across all elements. Special care is taken to ensure that every union operation is done via a find function with path compression to keep the tree flat and union-by-rank if desired (though rank is optional for n up to 100).