Number of Unique Categories - Problem
Number of 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 haveSameCategory function is guaranteed to be consistent
  • Interactive constraint: You can only determine categories through the given function

Visualization

Tap to expand
Category Detection VisualizationStep 1: Individual Elements01234Step 2: Check RelationshipsSame!Same!01234Step 3: Form CategoriesCategory AElements: 0, 1Category BElements: 2, 4Category CElement: 3Result: 3 Unique Categories Detected!
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
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
76.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen