1773. Count Items Matching a Rule
Explanation:
To solve this problem, we need to iterate through the given items array and count the number of items that match the given rule based on the ruleKey and ruleValue. We can simply compare the ruleKey and ruleValue with the corresponding values in each item to determine if it matches the rule.
- Initialize a counter to keep track of the number of items that match the rule.
- Iterate through each item in the items array.
- For each item, check if the ruleKey matches "type", "color", or "name" and compare the ruleValue with the corresponding value in the item.
- If a match is found, increment the counter.
- Finally, return the counter as the result.
Time Complexity:
The time complexity of this solution is O(n), where n is the number of items in the given array.
Space Complexity:
The space complexity is O(1) as we are using a constant amount of extra space.
:
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int count = 0;
for (List<String> item : items) {
if ((ruleKey.equals("type") && ruleValue.equals(item.get(0))) ||
(ruleKey.equals("color") && ruleValue.equals(item.get(1))) ||
(ruleKey.equals("name") && ruleValue.equals(item.get(2)))) {
count++;
}
}
return count;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.