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): Returns true if a and b are in the same category and false otherwise. Also, if either a or b is not a valid number (i.e. it's greater than or equal to n or less than 0), it returns false.

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
Number of Unique Categories ProblemElements (n=6):012345same categorysame categorysame categoryGrouped Categories:{0, 3}{1, 4}{2, 5}haveSameCategory() calls:haveSameCategory(0,3) → truehaveSameCategory(1,4) → truehaveSameCategory(2,5) → truehaveSameCategory(0,1) → falsehaveSameCategory(0,2) → false... and so onAnswer: 3 unique categories
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
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 4
12.3K Views
Medium Frequency
~25 min Avg. Time
456 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