Count Items Matching a Rule — LeetCode 1773 Python Solution

EasyArrayString
Problem
#1773
Pattern
Hash Map
Reading time
2 min

The 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.

Example

Input
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output
1
Explanation
There is only one item matching the given rule, which is ["computer","silver","lenovo"].

Python solution

Python
class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        i = 0 if ruleKey[0] == 't' else (1 if ruleKey[0] == 'c' else 2)
        return sum(v[i] == ruleValue for v in items)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1773. Count Items Matching a Rule is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1773. Count Items Matching a Rule?
LeetCode 1773. Count Items Matching a Rule is rated Easy on LeetCode.
What topics does LeetCode 1773. Count Items Matching a Rule cover?
LeetCode 1773. Count Items Matching a Rule is tagged Array and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview