## Similar Problems

Similar Problems not available

# Count Items Matching A Rule - Leetcode Solution

## Companies:

LeetCode: Count Items Matching A Rule Leetcode Solution

Difficulty: Easy

Problem description:

You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.

The ith item is said to match the rule if one of the following is true:

- ruleKey == "type" and ruleValue == typei.
- ruleKey == "color" and ruleValue == colori.
- ruleKey == "name" and ruleValue == namei.

Return the number of items that match the given rule.

Example 1:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver" Output: 1 Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

Solution:

We can solve this problem by iterating over each item in the given items array and checking if it matches the given rule using the conditions mentioned in the problem statement.

We can keep a count of the number of items that match the given rule and return the count as the final answer.

Below is the implementation of the solution in Python:

def countMatches(items, ruleKey, ruleValue): count = 0 for item in items: if ruleKey == "type" and ruleValue == item[0]: count += 1 elif ruleKey == "color" and ruleValue == item[1]: count += 1 elif ruleKey == "name" and ruleValue == item[2]: count += 1 return count

The above code checks each item in the items array and increments the count variable if the item matches the given rule.

We have used if-elif statements to check if the rule matches the conditions mentioned in the problem statement.

Finally, we return the count variable as the final answer.

Time Complexity:

The above solution iterates over each item in the items array exactly once and checks if it matches the given rule. So, the time complexity of this solution is O(n), where n is the length of the items array.

Space Complexity:

The above solution uses a constant amount of extra space for the count variable. So, the space complexity of this solution is O(1).

## Count Items Matching A Rule Solution Code

`1`