Count Items Matching a Rule - Problem
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"andruleValue == typeiruleKey == "color"andruleValue == coloriruleKey == "name"andruleValue == namei
Return the number of items that match the given rule.
Input & Output
Example 1 — Color Filter
$
Input:
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
›
Output:
1
💡 Note:
Only the computer item has color "silver", so count = 1
Example 2 — Type Filter
$
Input:
items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
›
Output:
2
💡 Note:
First and third items have type "phone", so count = 2
Example 3 — No Matches
$
Input:
items = [["phone","blue","pixel"],["computer","silver","lenovo"]], ruleKey = "name", ruleValue = "iphone"
›
Output:
0
💡 Note:
No items have name "iphone", so count = 0
Constraints
- 1 ≤ items.length ≤ 104
- 1 ≤ typei.length, colori.length, namei.length, ruleValue.length ≤ 10
- ruleKey is equal to either "type", "color", or "name"
- All strings consist only of lowercase letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of items and rule (key, value)
2
Process
Check each item's attribute against rule
3
Output
Count of matching items
Key Takeaway
🎯 Key Insight: Map rule key to array index once, then use direct access for efficient filtering
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code