Domain 2MediumMEDIUM

Market Analysis I

Filter customers from 'USA' with age > 30 using a single linear pass through the dataset, checking country string equality and numeric age constraints."

Domain: medium•Updated: 2026-09-09
#filtering#list iteration#O(N)#O(K)

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 (O(N)O(N)). 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

  1. 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.
  2. Iterate: Loop through each record in the input collection.
  3. Filter Logic: For every record:
    • Verify country matches 'USA'. Note that string comparison must be exact (case-sensitive).
    • Ensure age is a valid numeric type (int or float) to avoid TypeErrors when comparing with integers in Python, as None > 30 raises an exception.
    • Verify the value of age is strictly greater than 30.
  4. Collect: If both conditions are met, append the ID to the result list.
  5. Return: Return the populated list.

Complexity Analysis

  • Time Complexity: O(N)O(N), where NN 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: O(K)O(K) auxiliary space (excluding input), where KK is the number of matching records stored in our result list. In the worst case, all rows match (K=NK=N).

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 (O(1)O(1)).
  • No Matches: If no rows satisfy the condition, qualified_ids remains empty and returns correctly.
  • NULL/None Ages: Using .get() for country safety (though direct access used in logic) combined with isinstance(record['age'], ...) ensures that if age is missing or explicitly set to None, it fails the type check before comparison, preventing a TypeError which would occur directly comparing None > 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”.