Number of Unique Categories - Problem
Number of Unique Categories
You're working as a data analyst for a large company that needs to categorize
Instead, you have access to a
Your goal: Find the total number of unique categories among all items.
Example: If items [0,1,2,3,4] have categories [A,A,B,C,B], then there are 3 unique categories.
You're working as a data analyst for a large company that needs to categorize
n items (numbered from 0 to n-1). Each item belongs to exactly one category, but you don't know the categories directly.Instead, you have access to a
CategoryHandler object with a special method:boolean haveSameCategory(int a, int b): Returns true if items a and b belong to the same category, false otherwise. If either a or b is invalid (< 0 or >= n), it returns false.Your goal: Find the total number of unique categories among all items.
Example: If items [0,1,2,3,4] have categories [A,A,B,C,B], then there are 3 unique categories.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 5
Categories: [A, A, B, C, B]
haveSameCategory(0,1) = true
haveSameCategory(0,2) = false
haveSameCategory(2,4) = true
...
โบ
Output:
3
๐ก Note:
There are 3 unique categories: A (elements 0,1), B (elements 2,4), and C (element 3)
example_2.py โ All Same Category
$
Input:
n = 4
Categories: [X, X, X, X]
haveSameCategory(i,j) = true for all i,j
โบ
Output:
1
๐ก Note:
All elements belong to the same category X, so there's only 1 unique category
example_3.py โ All Different Categories
$
Input:
n = 3
Categories: [P, Q, R]
haveSameCategory(i,j) = false for all iโ j
โบ
Output:
3
๐ก Note:
Each element is in its own unique category, so there are 3 unique categories
Constraints
- 1 โค n โค 100
-
The
haveSameCategoryfunction is guaranteed to be consistent - Interactive constraint: You can only determine categories through the given function
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with each person in their own group
2
Ask Questions
For each pair, ask if they're friends (same category)
3
Merge Groups
When friends are found, merge their social circles
4
Count Groups
Final number of separate friend groups
Key Takeaway
๐ฏ Key Insight: Union-Find efficiently tracks which elements belong together, automatically counting distinct groups as we discover relationships
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code