#1773

Count Items Matching a Rule

Easy
ArrayStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses the same logic as brute force but is more efficient by directly indexing into the item based on the ruleKey, which reduces unnecessary checks.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a mapping for ruleKey to the corresponding index in the item array.
  2. 2Step 2: Use the index to directly access the relevant attribute of each item.
  3. 3Step 3: Initialize a counter to zero.
  4. 4Step 4: Iterate through each item and check if the attribute at the mapped index matches ruleValue.
  5. 5Step 5: Increment the counter for each match and return it.
solution.py7 lines
1def countMatches(items, ruleKey, ruleValue):
2    keyIndex = {'type': 0, 'color': 1, 'name': 2}
3    count = 0
4    for item in items:
5        if item[keyIndex[ruleKey]] == ruleValue:
6            count += 1
7    return count

Complexity note: The time complexity remains O(n) as we still iterate through the items. The space complexity is O(1) since we use a fixed amount of extra space.

  • 1Directly mapping ruleKey to indices improves efficiency.
  • 2Understanding the structure of the data helps in optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.