You are given an integer n and an object categoryHandler of class
CategoryHandler.
There are n elements, numbered from 0 to n - 1. Each element has a category, and your task is to find the number of unique categories.
The class CategoryHandler contains the following function, which may help you:
boolean haveSameCategory(integer a, integer b): Returns true if a and b are in the same category and false otherwise. Also, if either a or b is not a valid number (i.e. it’s greater than or equal to nor less than 0), it returns false.
Input: n =6, categoryHandler =[1,1,2,2,3,3]Output: 3Explanation: There are 6 elements inthis example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories.
Example 2:
1
2
3
Input: n =5, categoryHandler =[1,2,3,4,5]Output: 5Explanation: There are 5 elements inthis example. Each element belongs to a unique category. So there are 5 unique categories.
Example 3:
1
2
3
Input: n =3, categoryHandler =[1,1,1]Output: 1Explanation: There are 3 elements inthis example. All of them belong to one category. So there is only 1 unique category.
We can use union-find to group elements that are in the same category. For each pair (i, j), if haveSameCategory(i, j) is true, we union them. The number of unique categories is the number of unique roots.
classSolution {
publicintnumberOfCategories(int n, CategoryHandler categoryHandler) {
int[] parent =newint[n];
for (int i = 0; i < n; i++) parent[i]= i;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (categoryHandler.haveSameCategory(i, j)) union(parent, i, j);
}
}
Set<Integer> roots =new HashSet<>();
for (int i = 0; i < n; i++) roots.add(find(parent, i));
return roots.size();
}
privateintfind(int[] parent, int x) {
if (parent[x]!= x) parent[x]= find(parent, parent[x]);
return parent[x];
}
privatevoidunion(int[] parent, int x, int y) {
parent[find(parent, x)]= find(parent, y);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defnumberOfCategories(self, n: int, categoryHandler: 'CategoryHandler') -> int:
parent = list(range(n))
deffind(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
defunion(x, y):
parent[find(x)] = find(y)
for i in range(n):
for j in range(i+1, n):
if categoryHandler.haveSameCategory(i, j):
union(i, j)
return len(set(find(i) for i in range(n)))