Problem Description
Given a list of items where each item is represented as an array of strings [type, color, name], determine the number of items that satisfy a specific rule. The rule is defined by a key (either "type", "color", or "name") and a corresponding value. An item matches the rule if the value corresponding to the ruleKey is equal to the given ruleValue.
Key Insights
- Map the ruleKey ("type", "color", or "name") to the respective index in the item list (0 for type, 1 for color, 2 for name).
- Iterate over each item and count how many items have the attribute matching the provided ruleValue.
- This approach leverages simple indexing and comparison, making it efficient and straightforward.
Space and Time Complexity
Time Complexity: O(n), where n is the number of items. Space Complexity: O(1) extra space, since the solution uses a constant amount of additional memory.
Solution
The solution involves mapping the given ruleKey to the correct index for each item, then iterating through the list of items while comparing the value at that index with the ruleValue. Every time a match is found, a counter is incremented. At the end of the iteration, the counter is returned. This approach ensures that each item is examined only once, making the solution efficient in terms of time and space.