Problem 1773

Abstract / Summary

Count how many items have all properties matching the given rule.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1773.py

class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        result = 0
        for type, color, name in items:
            if   ruleKey == "type"  and type  == ruleValue:
                result += 1
            elif ruleKey == "color" and color == ruleValue:
                result += 1
            elif ruleKey == "name"  and name  == ruleValue:
                result += 1
        return result
11 lines | 461 bytes | submitted December 23, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method countMatches. The method receives a collection of items, each represented as a list of three strings (type, color, name), together with a ruleKey and a ruleValue. Its purpose is to count how many items satisfy the rule expressed by the pair (ruleKey, ruleValue). The algorithm iterates over the input list once, evaluates the rule for each item, and increments a counter when the rule holds. Finally, the accumulated count is returned.

Key Steps

Extraction of Fields

At the start of the loop the code unpacks each inner list into three distinct variables, allowing direct reference to the semantic components of an item.

for type, color, name in items:

This unpacking eliminates the need for index-based access and makes the subsequent condition checks more readable.

Rule Matching Logic

The core decision structure consists of three mutually exclusive conditional branches, each corresponding to one possible value of ruleKey. The branches compare the appropriate field with ruleValue.

if   ruleKey == "type"  and type  == ruleValue:
    result += 1
elif ruleKey == "color" and color == ruleValue:
    result += 1
elif ruleKey == "name"  and name  == ruleValue:
    result += 1

Only the branch that matches the supplied ruleKey performs a comparison; the others are bypassed, ensuring that exactly one field is examined per iteration.

Result Accumulation

When a comparison succeeds, the method increments a running total stored in result. The increment operation is straightforward and occurs inside each conditional branch.

result += 1

After processing all items, the method returns the final count.

return result

Edge Cases Handled

The algorithm gracefully handles an empty items list. Since the loop body never executes, result remains at its initial value of zero, and the method correctly returns zero matches.

When ruleKey is supplied with a value outside the expected set ("type", "color", "name"), none of the conditional branches evaluate to true, and the counter is never incremented. This behavior effectively treats unknown rule keys as yielding zero matches without raising an exception.

The code also tolerates items that contain exactly three elements, as required by the unpacking pattern. If an inner list were shorter or longer, Python would raise a ValueError, but within the intended contract of the method-where each item is guaranteed to have three attributes-this situation does not arise.

Performance Optimizations

The implementation processes the input in a single pass, performing a constant amount of work per item. By unpacking the item tuple once and using direct variable references, it avoids repeated indexing operations that could add overhead.

The use of elif ensures that once a matching ruleKey is found, the remaining branches are not evaluated. This short-circuiting eliminates unnecessary comparisons, especially when the rule key is known early in the sequence.

Incrementing a simple integer counter (result) is an O(1) operation, and returning the final value after the loop avoids any additional data structures or intermediate collections, keeping memory usage minimal.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box filled with many toys. Each toy has three special labels attached to it, which are its type, its color, and its name. This code acts like a tiny helper with a clipboard who wants to count how many toys match a specific sticker.

The helper starts with a count of zero. Then, it picks up every single toy from the box one by one to look at the three labels. If the helper is looking for a specific type, it checks the type label. If the helper is looking for a specific color, it checks the color label instead. If the helper is looking for a specific name, it checks the name label. Whenever the label on a toy matches the secret sticker the helper is holding, it clicks a counter to add one more to the total. After all the toys have been checked, the counting is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.15 | σ = 0.76

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go C Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
31 links | 19 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality