We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Items Matching a Rule

Number: 1899

Difficulty: Easy

Paid? No

Companies: Apple, Amazon, Meta


Problem Description

Given a list of items where each item is represented as an array of strings [type, color, name], determine the number of items that satisfy a specific rule. The rule is defined by a key (either "type", "color", or "name") and a corresponding value. An item matches the rule if the value corresponding to the ruleKey is equal to the given ruleValue.


Key Insights

  • Map the ruleKey ("type", "color", or "name") to the respective index in the item list (0 for type, 1 for color, 2 for name).
  • Iterate over each item and count how many items have the attribute matching the provided ruleValue.
  • This approach leverages simple indexing and comparison, making it efficient and straightforward.

Space and Time Complexity

Time Complexity: O(n), where n is the number of items. Space Complexity: O(1) extra space, since the solution uses a constant amount of additional memory.


Solution

The solution involves mapping the given ruleKey to the correct index for each item, then iterating through the list of items while comparing the value at that index with the ruleValue. Every time a match is found, a counter is incremented. At the end of the iteration, the counter is returned. This approach ensures that each item is examined only once, making the solution efficient in terms of time and space.


Code Solutions

# Define the function that takes items, ruleKey, and ruleValue as inputs
def countMatches(items, ruleKey, ruleValue):
    # Map each ruleKey to its corresponding index in the item list
    key_to_index = {"type": 0, "color": 1, "name": 2}
    index = key_to_index[ruleKey]  # Get the correct index for comparison
    count = 0  # Initialize counter for matching items
    
    # Iterate through each item in the list
    for item in items:
        # Check if the item attribute matches the ruleValue at the mapped index
        if item[index] == ruleValue:
            count += 1  # Increment the counter if there's a match
    return count

# Example usage:
items = [["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]]
print(countMatches(items, "color", "silver"))  # Output: 1
← Back to All Questions