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 INPUT n = 6 elements (0 to 5) 0 1 2 3 4 5 categories array: 0 [0] 1 [1] 2 [2] 0 [3] 1 [4] 2 [5] CategoryHandler API: haveSameCategory(a,b) Returns true if same category, false otherwise ALGORITHM STEPS (Union-Find / DSU) 1 Initialize DSU Each element is its own parent parent = [0,1,2,3,4,5] 2 Compare All Pairs For each pair (i,j) call haveSameCategory(i, j) 3 Union Same Category If true, union(i, j) 0--3, 1--4, 2--5 4 Count Unique Roots Count elements where find(i) == i Union Operations: 0, 3 1, 4 2, 5 3 distinct sets formed FINAL RESULT After all unions completed: Category 0 0 3 root: 0 Category 1 1 4 root: 1 Category 2 2 5 root: 2 Output: 3 OK - 3 unique categories found using Union-Find Key Insight: Union-Find efficiently groups elements with the same category. By comparing all pairs using haveSameCategory() and unioning matching pairs, we create disjoint sets. The number of unique roots equals the number of unique categories. Time: O(n^2 * alpha(n)) where alpha is inverse Ackermann. Space: O(n) for parent array. TutorialsPoint - Number of Unique Categories | Union-Find (Disjoint Set Union) Approach
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