Number of Unique Categories Problem
Description
LeetCode Problem 2782.
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): Returnstrueifaandbare in the same category andfalseotherwise. Also, if eitheraorbis not a valid number (i.e. it's greater than or equal tonor less than0), it returnsfalse.
Return the number of unique categories.
Example 1:
Input: n = 6, categoryHandler = [1,1,2,2,3,3]
Output: 3
Explanation: There are 6 elements in this 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:
Input: n = 5, categoryHandler = [1,2,3,4,5]
Output: 5
Explanation: There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories.
Example 3:
Input: n = 3, categoryHandler = [1,1,1]
Output: 1
Explanation: There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category.
Constraints:
1 <= n <= 100
Solution
Approach: Union-Find
The only way to learn about categories is to ask haveSameCategory(a, b). With n <= 100 we can afford to ask about every pair. Keep a disjoint set over the indices and, whenever a pair is in the same category, merge their sets. After all pairs have been asked, the number of sets is the number of categories, that is, the number of indices that are their own root.
Complexity: O(n^2) calls to haveSameCategory and O(n) extra space.
# Definition for a category handler.
# class CategoryHandler:
# def haveSameCategory(self, a: int, b: int) -> bool:
# pass
class Solution:
def numberOfCategories(
self, n: int, categoryHandler: Optional['CategoryHandler']
) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
for a in range(n):
for b in range(a + 1, n):
if categoryHandler.haveSameCategory(a, b):
p[find(a)] = find(b)
return sum(i == x for i, x in enumerate(p))