Problem Breakdown
The problem requires filtering a list of customer records based on two specific conditions: country must be exactly 'USA' (case-sensitive) and age must be strictly greater than 30. The output should be the unique identifiers (customer_id) for all matching customers.
Inputs: A collection representing database rows, typically a list of dictionaries containing keys like customer_id, country, and age.
Outputs: A list of integers or strings corresponding to valid customer IDs.
Intuition
The most efficient way to solve this is to iterate through the dataset exactly once (). Since we are filtering based on simple predicates without needing aggregation, sorting, or complex joins, a linear scan is optimal for unindexed memory structures (like Python lists) simulating database rows. We must inspect every record because any row could potentially match the criteria.
Approach
- Initialize: Create an empty list to store qualifying
customer_ids. A set could be used if duplicate IDs were possible, but primary keys usually ensure uniqueness; a list preserves order which is standard for SQL result sets unless specified otherwise. - Iterate: Loop through each record in the input collection.
- Filter Logic: For every record:
- Verify
countrymatches'USA'. Note that string comparison must be exact (case-sensitive). - Ensure
ageis a valid numeric type (intorfloat) to avoid TypeErrors when comparing with integers in Python, asNone > 30raises an exception. - Verify the value of
ageis strictly greater than30.
- Verify
- Collect: If both conditions are met, append the ID to the result list.
- Return: Return the populated list.
Complexity Analysis
- Time Complexity: , where is the number of customers in the table. We perform a constant-time check for each row during a single linear scan. No sorting or repeated passes are required.
- Space Complexity: auxiliary space (excluding input), where is the number of matching records stored in our result list. In the worst case, all rows match ().
Solution
def market_analysis(customers):
"""
Filters customers from 'USA' who are older than 30 years old.
Args:
customers (List[Dict]): List of dictionaries representing customer records
with keys 'customer_id', 'country', and 'age'.
Returns:
List[Any]: A list of unique customer IDs meeting the criteria.
Note: ID type matches input schema (int or str).
"""
qualified_ids = []
for record in customers:
# Check country match (case-sensitive) and age constraint (> 30)
# Using .get() ensures safety if keys are missing, though schema implies existence.
# isinstance check prevents TypeError when comparing None/Non-numeric ages to integers.
if record.get('country') == 'USA' \
and isinstance(record['age'], (int, float)) \
and record['age'] > 30:
qualified_ids.append(record['customer_id'])
return qualified_ids
# Example usage for verification:
if __name__ == "__main__":
sample_data = [
{"customer_id": "1", "country": "USA", "age": 35},
{"customer_id": "2", "country": "Canada", "age": 40},
{"customer_id": "3", "country": "usa", "age": 36}, # Case mismatch -> Excluded
{"customer_id": "4", "country": "USA", "age": None} # Null age check handled by isinstance -> False
]
result = market_analysis(sample_data)
print(result)
Edge Cases Handled
- Empty Input: The loop simply does not execute; an empty list is returned immediately ().
- No Matches: If no rows satisfy the condition,
qualified_idsremains empty and returns correctly. - NULL/None Ages: Using
.get()for country safety (though direct access used in logic) combined withisinstance(record['age'], ...)ensures that if age is missing or explicitly set toNone, it fails the type check before comparison, preventing a TypeError which would occur directly comparingNone > 30. - Case Sensitivity: The string
'USA'matches exactly. A record with country'usa'will be excluded as per standard SQL behavior unless collation is specified otherwise (handled by strict equality). - Age Boundary: Strictly checks
> 30, excluding customers who are exactly 30 years old, matching the requirement “older than”.