Magicsheet logo

Count Items Matching a Rule

Easy
12.5%
Updated 8/1/2025

Asked by 3 Companies

Count Items Matching a Rule

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

Items: [["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]] Rule: ruleKey = "type", ruleValue = "phone"

  1. "type" corresponds to index 0.
  2. Item 0: index 0 is "phone". Match!
  3. Item 1: index 0 is "computer". No match.
  4. Item 2: index 0 is "phone". Match! Total count: 2.

Common mistakes candidates make

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.

Interview preparation tip

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.

Similar Questions