#1773
Count Items Matching a Rule
Easy List of lists
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Each item is a list [type, color, name]. Given a rule key ("type", "color" or "name") and a value, count items whose matching field equals the value.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: look at one field (type, color or name) of each item and count matches.
Why this works: convert the rule key to a column index once, then each item is a single equals() check.
Example: ruleKey = "color", ruleValue = "silver"
index = 1["phone","blue","pixel"] → blue ≠ silver["computer","silver","lenovo"] → match["phone","gold","iphone"] → gold ≠ silveranswer: 1
✦Hints open one at a time
Map the rule key to an index 0, 1 or 2 once, before the loop.
Compare strings with equals(), not ==.
↗Approach
Convert ruleKey to a column index, then loop over the items and compare item.get(index) with ruleValue.
</>Solution (Java)
import java.util.*;
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int idx = ruleKey.equals("type") ? 0 : ruleKey.equals("color") ? 1 : 2;
int count = 0;
for (List<String> item : items) {
if (item.get(idx).equals(ruleValue)) count++;
}
return count;
}
}
!Common mistake
Using == on Strings, which compares references and can fail even when the text matches.
