Leetcode 1773: Count Items Matching a Rule

grid47
grid47
Exploring patterns and algorithms
May 13, 2024 5 min read

You are given an array items, where each items[i] represents the type, color, and name of the ith item. You are also given a rule consisting of two strings: ruleKey and ruleValue. The task is to count how many items match the rule. An item matches the rule if one of the following conditions is true:

  • ruleKey == 'type' and ruleValue matches the type of the item.
  • ruleKey == 'color' and ruleValue matches the color of the item.
  • ruleKey == 'name' and ruleValue matches the name of the item.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `items` containing lists of strings, each representing an item with a type, color, and name. The rule is represented by two strings: `ruleKey` and `ruleValue`.
Example: items = [['laptop', 'black', 'dell'], ['phone', 'blue', 'pixel'], ['tablet', 'gold', 'samsung']], ruleKey = 'color', ruleValue = 'blue'
Constraints:
• 1 <= items.length <= 10^4
• 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
• ruleKey is one of 'type', 'color', or 'name'.
• All strings consist only of lowercase letters.
Output: Return the number of items that match the given rule.
Example: Output: 1
Constraints:
• The result should be an integer representing the count of matching items.
Goal: The goal is to iterate over the items and check if they match the rule based on the given `ruleKey` and `ruleValue`.
Steps:
• Identify the index for the ruleKey (0 for 'type', 1 for 'color', 2 for 'name').
• Loop through the items and check if the value at the index corresponding to the ruleKey matches the ruleValue.
• Increment the counter for each match found.
Goal: The solution must handle a variety of input sizes and strings efficiently.
Steps:
• The solution must handle up to 10^4 items in the array.
• All strings should consist only of lowercase alphabetic characters.
Assumptions:
• The input array will contain at least one item.
• The ruleKey will always be one of 'type', 'color', or 'name'.
Input: items = [['laptop', 'black', 'dell'], ['phone', 'blue', 'pixel'], ['tablet', 'gold', 'samsung']], ruleKey = 'color', ruleValue = 'blue'
Explanation: In this example, there is only one item that matches the color 'blue', which is the second item ['phone', 'blue', 'pixel'].

Input: items = [['laptop', 'black', 'dell'], ['phone', 'blue', 'pixel'], ['tablet', 'black', 'samsung']], ruleKey = 'type', ruleValue = 'phone'
Explanation: In this case, only one item matches the type 'phone', which is the second item ['phone', 'blue', 'pixel'].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus