Leetcode #2782: Number of Unique Categories
In this guide, we solve Leetcode #2782 Number of Unique Categories in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer n and an object categoryHandler of class CategoryHandler. There are n elements, numbered from 0 to n - 1.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Union Find, Counting, Interactive
Intuition
We need to merge components and check connectivity efficiently.
Union-Find supports near-constant-time merges and finds.
Approach
Initialize each node as its own parent and union pairs as you scan.
Use path compression to keep operations fast.
Steps:
- Initialize parent arrays.
- Union related nodes.
- Use find to check connectivity.
Example
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.
Python Solution
# 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))
Complexity
The time complexity is Near O(n) (amortized). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.