Leetcode 1773. Count Items Matching a Rule
In LeetCode problem 1773, you’re given a list of items, where each item is represented as a list of strings. Each item contains exactly three strings in the order: type, color, and name. Additionally, you are provided with a rule represented by two strings: a ruleKey
and a ruleValue
. The ruleKey
can be either “type”, “color”, or “name”.
You need to count the number of items that match the given rule. Specifically, you are to return the number of items for which the value specified by the ruleKey
equals the ruleValue
.
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
ruleKey
can be “type”, “color”, or “name”, we can map these to indices 0, 1, or 2, respectively.
Iterate Over Items: Iterate over each item in the list and use the mapped index to check if the item’s value at that index equals ruleValue
.
Here’s the code implementing the above-mentioned strategy:
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int index;
// Map ruleKey to the corresponding index
if (ruleKey == "type") {
index = 0;
} else if (ruleKey == "color") {
index = 1;
} else {
index = 2;
}
int count = 0;
// Iterate through each item and count matches
for (auto& item : items) {
if (item[index] == ruleValue) {
count++;
}
}
return count;
}
};
The time complexity of this approach is O(n), where n
is the number of items in the list. This is because we iterate over each item once.
Therefore, the overall time complexity is O(n).
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?