algoadvance

You are given a list of items, where each items[i] = [type_i, color_i, name_i] describes the type, color, and name of the i-th item. You are also given a ruleKey and a ruleValue.

You need to return the number of items that match the given rule. The rule is defined as follows:

Example 1

Input:

items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "color"
ruleValue = "silver"

Output:

1

Example 2

Input:

items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey = "type"
ruleValue = "phone"

Output:

2

Clarifying Questions

  1. What is the maximum size of items list?
    • This would help in understanding if any performance optimization is needed.
  2. Are the values in ruleKey always among type, color, name?
    • This ensures the validity of inputs.
  3. Is it guaranteed that items will have three components - type, color, name?
    • To ensure consistent input for processing.

With these clarifications, we can proceed to solve the problem.

Strategy

  1. Determine the Index to Compare:
    • Map ruleKey to the corresponding index: “type” -> 0, “color” -> 1, “name” -> 2.
  2. Iterate Over Items:
    • Count items where the element at the mapped index matches ruleValue.
  3. Return the Count:
    • Output the total matching items count.

Code

def countMatches(items, ruleKey, ruleValue):
    # Mapping `ruleKey` to their respective index in the list
    key_to_index = {"type": 0, "color": 1, "name": 2}
    
    # Determine the index to be used for comparison
    index = key_to_index[ruleKey]
    
    # Count the matching items
    count = 0
    for item in items:
        if item[index] == ruleValue:
            count += 1
    
    return count

# Test examples
items1 = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey1 = "color"
ruleValue1 = "silver"
print(countMatches(items1, ruleKey1, ruleValue1))  # Output: 1

items2 = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
ruleKey2 = "type"
ruleValue2 = "phone"
print(countMatches(items2, ruleKey2, ruleValue2))  # Output: 2

Time Complexity

This approach efficiently counts the items matching the rule provided.

Try our interview co-pilot at AlgoAdvance.com