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" and ruleValue == typei
  • ruleKey == "color" and ruleValue == colori
  • ruleKey == "name" and ruleValue == 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
Count Items Matching Rule: Find items where color = "silver"Item 1phonebluepixelItem 2computersilver ✓lenovoItem 3phonegoldiphoneRule: ruleKey = "color", ruleValue = "silver"Match Found!Count = 1Output: 1
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
Asked in
Amazon 15 Microsoft 8
34.8K Views
Medium Frequency
~5 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen