Domain 2MediumMEDIUM

Countries You Can Safely Invest In

Filters a dataset of country records based on population and income thresholds, returning unique names that meet safety criteria using efficient single-pass logic.

Domain: medium•Updated: 2026-09-17
#filtering#set-operations#O(n)#O(k)

Problem Breakdown

The problem requires filtering a collection of country data to identify those meeting specific investment safety metrics.

Inputs:

  • A dataset (list of dictionaries) containing attributes like name, population (int), and optionally an income/stability metric (income).
  • Threshold values defining “safe” conditions (e.g., minimum population, maximum risk).

Outputs:

  • A list of unique country names that satisfy all safety criteria.

Implicit Constraints & Edge Cases:

  • Nulls/Empty Data: Rows with missing critical data must be excluded to prevent runtime errors during comparison operations.
  • Uniqueness: SQL queries typically return distinct results (SELECT DISTINCT). If the input contains duplicate records for a country, only one entry should appear in the output unless specified otherwise.
  • Threshold Boundaries: Conditions are generally inclusive (e.g., population >= 20M), aligning with standard business logic where meeting the threshold exactly qualifies as “safe”.

Intuition

A brute-force approach iterates through every record and checks conditions individually, which is inherently O(N)O(N). Since filtering is a linear operation, optimizing beyond this isn’t possible without changing data structures. However, in an interview context, demonstrating awareness of how to handle duplicates (using sets or distinct logic) and avoiding multiple passes shows seniority.

The key insight is that “safe investment” implies a deterministic filter operation (WHERE clause logic). We do not need complex algorithms like sorting unless ordering is requested later. The optimal approach leverages Python’s built-in filtering capabilities, specifically using set to ensure uniqueness of country names in the final output while maintaining O(N)O(N) time complexity for the pass over data.

Approach

  1. Define Criteria: Establish business rules via function arguments (e.g., min_population, optional income thresholds) rather than hardcoded constants where possible, allowing flexibility across different problem variations.
  2. Iterate & Filter: Loop through the input dataset once. For each record:
    • Validate existence and type of critical fields (name, population).
    • Check if values meet safety constraints (e.g., population ≥\ge threshold).
  3. Ensure Uniqueness: Use a Python set to collect qualifying country names, automatically handling duplicates during insertion. Convert back to list before returning for consistent ordering or JSON serialization requirements.
  4. Return: Output the sorted or ordered list of unique safe countries (optional sorting based on problem spec).

Complexity Analysis

  • Time Complexity: O(N)O(N) where NN is the number of country records. We visit each row exactly once during filtering. Set insertion and lookup are amortized O(1)O(1). Sorting at the end would be O(Klog⁡K)O(K \log K), but if order doesn’t matter or input preserves original order (via list comprehension), it remains dominated by the filter pass.
  • Space Complexity: O(K)O(K) where KK is the number of unique matching results stored in the output set/list. Auxiliary space excluding output is O(1)O(1).

Solution

def safe_countries(countries_data, min_population=20_000_000):
    """
    Filters countries based on investment safety criteria (Population >= Threshold).
    
    Args:
        countries_data (list[dict]): List of country records with keys 
                                     'name', 'population' (int/float), and optionally others.
        min_population (int): Minimum population required for stability. Default 20M.
        
    Returns:
        list[str]: Unique names of safe countries meeting the criteria, sorted alphabetically.
    """
    # Define safety thresholds based on typical business logic
    MIN_POPULATION = min_population
    
    if not countries_data or not isinstance(countries_data, list):
        return []

    seen_countries = set()  # Use set to handle duplicates and ensure uniqueness efficiently
    
    for country in countries_data:
        name = country.get('name')
        
        # Guard against nulls, empty strings, or non-string names
        if not isinstance(name, str) or not name.strip():
            continue
            
        population = country.get('population', 0)
        
        # Ensure population is numeric before comparison to avoid TypeError with None/null values
        try:
            pop_val = float(population) if population else 0.0
        except (TypeError, ValueError):
            pop_val = 0.0
            
        # Check primary stability constraint (Population >= Threshold)
        if pop_val < MIN_POPULATION:
            continue
        
        safe_countries_list.append(name)

    return list(seen_countries)