Skip to content

1773. Count Items Matching a Rule 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int countMatches(vector<vector<string>>& items, string ruleKey,
                   string ruleValue) {
    const int index = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2;
    return ranges::count_if(items, [index, &ruleValue](const auto& item) {
      return item[index] == ruleValue;
    });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
    if (ruleKey.equals("type"))
      return count(items, 0, ruleValue);
    if (ruleKey.equals("color"))
      return count(items, 1, ruleValue);
    return count(items, 2, ruleValue);
  }

  private int count(List<List<String>> items, int index, final String ruleValue) {
    return (int) items.stream()
        .map(item -> item.get(index))
        .filter(s -> s.equals(ruleValue))
        .count();
  }
}