Number of Unique Categories — LeetCode 2782 Python Solution

MediumLeetCode PremiumUnion FindCountingInteractive
Problem
#2782
Pattern
Union-Find
Reading time
3 min

The problem

You are given an integer n and an object categoryHandler of class CategoryHandler. There are n elements, numbered from 0 to n - 1.

Example

Input
n = 6, categoryHandler = [1,1,2,2,3,3]
Output
3
Explanation
There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories.

Python solution

Python
# Definition for a category handler.
# class CategoryHandler:
#     def haveSameCategory(self, a: int, b: int) -> bool:
#         pass
class Solution:
    def numberOfCategories(
        self, n: int, categoryHandler: Optional['CategoryHandler']
    ) -> int:
        def find(x: int) -> int:
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        p = list(range(n))
        for a in range(n):
            for b in range(a + 1, n):
                if categoryHandler.haveSameCategory(a, b):
                    p[find(a)] = find(b)
        return sum(i == x for i, x in enumerate(p))

Complexity

MeasureComplexity
TimeNear O(n) (amortized)
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 2782. Number of Unique Categories is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Union Find.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2782. Number of Unique Categories?
LeetCode 2782. Number of Unique Categories is rated Medium on LeetCode.
What is the time complexity of LeetCode 2782. Number of Unique Categories?
The Python solution on this page runs in Near O(n) (amortized).
What is the space complexity of LeetCode 2782. Number of Unique Categories?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2782. Number of Unique Categories cover?
LeetCode 2782. Number of Unique Categories is tagged Union Find, Counting and Interactive on LeetCode.
Is LeetCode 2782. Number of Unique Categories a premium problem?
Yes. LeetCode 2782. Number of Unique Categories is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview