Number of Unique Categories - Problem
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:
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.
Input & Output
Example 1 — Basic Case
$
Input:
n = 6, categories = [0, 1, 2, 0, 1, 2]
›
Output:
3
💡 Note:
Elements 0,3 are in category 0; elements 1,4 are in category 1; elements 2,5 are in category 2. Total unique categories = 3.
Example 2 — All Same Category
$
Input:
n = 4, categories = [1, 1, 1, 1]
›
Output:
1
💡 Note:
All elements 0,1,2,3 belong to the same category 1. Total unique categories = 1.
Example 3 — All Different Categories
$
Input:
n = 3, categories = [0, 1, 2]
›
Output:
3
💡 Note:
Each element is in a different category: 0→category 0, 1→category 1, 2→category 2. Total unique categories = 3.
Constraints
- 1 ≤ n ≤ 1000
- 0 ≤ element_id < n
- CategoryHandler.haveSameCategory() returns boolean
Visualization
Tap to expand
Understanding the Visualization
1
Input
n elements numbered 0 to n-1, each with a hidden category
2
Process
Use haveSameCategory() to find which elements belong together
3
Output
Count the number of distinct category groups
Key Takeaway
🎯 Key Insight: This is a graph connectivity problem where elements in the same category form connected components
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code