File: count-items-matching-a-rule/solution.py

Date: 2026-06-06

Time: 15:59

Purpose

This file solves LeetCode 1773 — Count Items Matching a Rule. It owns a single responsibility: given a list of items (each described by a type/color/name triple) and a filtering rule, count how many items match.

Key Components

Solution.countMatches — The only method. Takes a list of string triples, a rule key ("type", "color", or "name"), and a rule value. Returns the count of matching items.

The core trick is the dictionary lookup on line 14:


index = {"type": 0, "color": 1, "name": 2}[ruleKey]

This maps the semantic key name to its positional index in each [type, color, name] triple, then uses a generator expression to count matches in a single pass.

Patterns

Dependencies

Imports: typing.List only — no external or project-internal dependencies.

Imported by: The test_solution.py in the same directory. The long "Imported By" list in the prompt is misleading — those are test files for *other* problems that happen to share the same Solution class name pattern; they import from their own solution.py, not this one.

Flow

1. Translate ruleKey string to an integer index (0, 1, or 2).

2. Iterate over every item in items.

3. For each item, compare item[index] against ruleValue.

4. Sum up the matches and return.

Single pass, O(n) time, O(1) extra space.

Invariants

Error Handling

None. An invalid ruleKey produces an unhandled KeyError. This is appropriate for a LeetCode solution where inputs are guaranteed valid by the problem constraints.

Topics to Explore

Beliefs