In the "Count Items Matching a Rule" coding problem, you are given a list of items, where each item is described by its type, color, and name. You are also given a ruleKey (which can be "type", "color", or "name") and a ruleValue. Your task is to return the number of items that match the given rule.
This "Easy" problem is common at Meta and Amazon to test a candidate's ability to map strings to array indices and perform simple filtering. It evaluates basic string comparisons and the ability to write clean, concise code. It’s also a good test of whether a candidate understands how to access structured data stored in a list of lists.
The pattern is a Linear Scan with index mapping. Since the input is an array of triplets, you first determine which index (0, 1, or 2) corresponds to the ruleKey. Then, you iterate through the list of items once, checking if the value at that specific index matches the ruleValue.
Items: [["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]]
Rule: ruleKey = "type", ruleValue = "phone"
The most common mistake is using a series of inefficient if-else blocks inside the loop instead of determining the target index before the loop starts. Another mistake is hard-coding the strings "type", "color", and "name" in a way that is sensitive to case or typos.
For problems involving fixed-structure data (like triplets), use a small Map or a switch statement to translate the descriptive key into a numeric index. This separation of concerns makes your code more maintainable and demonstrates a "clean code" mindset.