Leetcode 1773. Count Items Matching a Rule
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 ruleKey
could be either “type”, “color”, or “name”. You need to count the number of items that match the given ruleKey
and ruleValue
.
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "color"
ruleValue = "silver"
Output:
1
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "type"
ruleValue = "phone"
Output:
2
ruleKey
?
items
array be empty?
0
.[type, color, name]
.ruleKey
.
ruleKey
is “type”, the index is 0.ruleKey
is “color”, the index is 1.ruleKey
is “name”, the index is 2.items
list and count the items that match the ruleValue
for the specified ruleKey
.Here’s the implementation in Java:
import java.util.List;
public class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int index = -1;
if ("type".equals(ruleKey)) {
index = 0;
} else if ("color".equals(ruleKey)) {
index = 1;
} else if ("name".equals(ruleKey)) {
index = 2;
}
int count = 0;
for (List<String> item : items) {
if (ruleValue.equals(item.get(index))) {
count++;
}
}
return count;
}
}
The time complexity of this solution is O(n)
, where n
is the number of items in the list. This is because we iterate through each item exactly once, performing a constant-time operation for each item.
items
list.ruleValue
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?