Skip to content

2782. Number of Unique Categories 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Definition for a category handler.
 * class CategoryHandler {
 *  public:
 *   CategoryHandler(vector<int> categories);
 *   bool haveSameCategory(int a, int b);
 * };
 */

class Solution {
 public:
  int numberOfCategories(int n, CategoryHandler* categoryHandler) {
    int ans = 0;

    for (int i = 0; i < n; ++i)
      if (!haveSameCategoryPreviously(i, n, categoryHandler))
        ++ans;

    return ans;
  }

 private:
  bool haveSameCategoryPreviously(int i, int n,
                                  CategoryHandler* categoryHandler) {
    for (int j = 0; j < i; ++j)
      if (categoryHandler->haveSameCategory(i, j))
        return true;
    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Definition for a category handler.
 * class CategoryHandler {
 *   public CategoryHandler(int[] categories);
 *   public boolean haveSameCategory(int a, int b);
 * };
 */

class Solution {
  public int numberOfCategories(int n, CategoryHandler categoryHandler) {
    int ans = 0;
    for (int i = 0; i < n; ++i)
      if (!haveSameCategoryPreviously(i, n, categoryHandler))
        ++ans;
    return ans;
  }

  private boolean haveSameCategoryPreviously(int i, int n, CategoryHandler categoryHandler) {
    for (int j = 0; j < i; ++j)
      if (categoryHandler.haveSameCategory(i, j))
        return true;
    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 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:
    ans = 0

    for i in range(n):
      if not any(categoryHandler.haveSameCategory(i, j) for j in range(i)):
        ans += 1

    return ans