Solving Leetcode Interviews in Seconds with AI: Count Items Matching a Rule
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1773" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. The ith item is said to match the rule if one of the following is true: ruleKey == "type" and ruleValue == typei. ruleKey == "color" and ruleValue == colori. ruleKey == "name" and ruleValue == namei. Return the number of items that match the given rule. Example 1: 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"]. Example 2: Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone" Output: 2 Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match. Constraints: 1 <= items.length <= 104 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 ruleKey is equal to either "type", "color", or "name". All strings consist only of lowercase letters.
Explanation
Here's the breakdown of the solution:
- Direct Mapping: Create a mapping (dictionary) from
ruleKeyvalues ("type", "color", "name") to the corresponding index in theitemsarray (0, 1, 2 respectively). This avoids multipleif/elsechecks, improving efficiency. - Iterate and Compare: Iterate through the
itemsarray, and for each item, use the mapping to directly access the relevant element (type, color, or name) based on theruleKey. Compare this element with theruleValue. Count Matches: Increment a counter each time a match is found.
Runtime Complexity: O(n), where n is the number of items. Storage Complexity: O(1) - The dictionary has a fixed size.
Code
def countMatches(items, ruleKey, ruleValue):
"""
Counts the number of items that match the given rule.
Args:
items: A list of lists, where each inner list represents an item.
ruleKey: The key to match against ("type", "color", or "name").
ruleValue: The value to match against.
Returns:
The number of items that match the rule.
"""
rule_map = {
"type": 0,
"color": 1,
"name": 2
}
index = rule_map[ruleKey]
count = 0
for item in items:
if item[index] == ruleValue:
count += 1
return count