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 a Rule INPUT items array: [0] phone blue pixel type color name [1] computer silver lenovo type color name [2] phone gold iphone type color name Rule: ruleKey "color" ruleValue "silver" Index Map: type:0, color:1, name:2 ALGORITHM STEPS 1 Map ruleKey to index "color" maps to index 1 2 Initialize count = 0 count = 0 3 Loop through items Check item[1] == "silver" i=0: "blue" == "silver"? NO i=1: "silver" == "silver"? OK i=2: "gold" == "silver"? NO count++ when match found 4 Return count return 1 Time: O(n) | Space: O(1) FINAL RESULT Matching Item Found: items[1]: computer silver lenovo color matches "silver" Non-matching items: [0] phone, blue, pixel [2] phone, gold, iphone Output: 1 1 item matches the rule Key Insight: Index Mapping Optimization Instead of using if-else chains, map ruleKey strings to array indices: {"type": 0, "color": 1, "name": 2}. This allows O(1) index lookup and direct comparison: items[i][index] == ruleValue. This approach eliminates branching and makes the code cleaner and more maintainable. TutorialsPoint - Count Items Matching a Rule | Index Mapping Optimization
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