Filter Person Records with Optional Bounds

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a directory of employee or candidate records people, write filter_people to extract every record that satisfies a configurable set of optional search filters while preserving original list order:

def filter_people(
    people: List[Dict[str, object]],
    min_age: Optional[int],
    max_age: Optional[int],
    occupations: Optional[List[str]],
    min_salary: Optional[int],
    max_salary: Optional[int],
) -> List[Dict[str, object]]:

Each dictionary in people contains five fields: - first_name (str) - last_name (str) - age (int) - occupation (str) - salary (int)

Filtering rules: - Logical AND across active checks: A record is kept only if it satisfies every parameter that is not None. - Independent None toggles: Passing None for any parameter turns off only that individual check (min_age = 28, max_age = None enforces age >= 28 with no upper ceiling). - Inclusive numeric bounds: - When min_age is not None, require age >= min_age. - When max_age is not None, require age <= max_age. - When min_salary is not None, require salary >= min_salary. - When max_salary is not None, require salary <= max_salary. - Case-sensitive occupation membership: When occupations is not None, it is a non-empty list of allowed role strings, and person["occupation"] must match one of them with exact capitalization. - Immutability & fresh output: Return a newly allocated list in the same relative order as people. Never modify people, any record dictionary inside it, or occupations.

Examples

Example 1

Input:
  people = [
    {"first_name": "Leo",  "last_name": "Tran",   "age": 24, "occupation": "analyst",   "salary": 92000},
    {"first_name": "Nora", "last_name": "Patel",  "age": 31, "occupation": "nurse",     "salary": 88000},
    {"first_name": "Omar", "last_name": "Silva",  "age": 38, "occupation": "analyst",   "salary": 76000},
    {"first_name": "Zoe",  "last_name": "Chen",   "age": 44, "occupation": "therapist", "salary": 91000},
    {"first_name": "Eli",  "last_name": "Brooks", "age": 29, "occupation": "nurse",     "salary": 95000},
  ]
  min_age = 28, max_age = 40
  occupations = ["analyst", "nurse"]
  min_salary = 85000, max_salary = None

Output:
  [
    {"first_name": "Nora", "last_name": "Patel",  "age": 31, "occupation": "nurse", "salary": 88000},
    {"first_name": "Eli",  "last_name": "Brooks", "age": 29, "occupation": "nurse", "salary": 95000},
  ]

Walk-through: Leo fails age >= 28, Omar fails salary >= 85000, and Zoe fails both age <= 40 and occupations. Nora and Eli pass every active filter and appear in their original order.

Example 2

Input:
  people = [
    {"first_name": "Maya", "last_name": "Ross",  "age": 26, "occupation": "Pharmacist", "salary": 115000},
    {"first_name": "Dan",  "last_name": "Ortiz", "age": 26, "occupation": "pharmacist", "salary": 115000},
  ]
  min_age = 26, max_age = 26
  occupations = ["Pharmacist"]
  min_salary = 115000, max_salary = 115000

Output:
  [
    {"first_name": "Maya", "last_name": "Ross", "age": 26, "occupation": "Pharmacist", "salary": 115000},
  ]

Walk-through: Numeric ranges are inclusive at both endpoints (26 and 115000 match), and occupation matching is case-sensitive ("Pharmacist" matches Maya while rejecting Dan's lowercase "pharmacist").

Example 3

Input:
  people = [
    {"first_name": "Kai", "last_name": "Bell", "age": 19, "occupation": "intern", "salary": 0},
    {"first_name": "Pia", "last_name": "Ward", "age": 22, "occupation": "intern", "salary": 18000},
  ]
  min_age = None, max_age = None
  occupations = None
  min_salary = None, max_salary = 0

Output:
  [
    {"first_name": "Kai", "last_name": "Bell", "age": 19, "occupation": "intern", "salary": 0},
  ]

Walk-through: max_salary = 0 is an active upper cap rather than a disabled filter, so Kai (salary == 0) is kept and Pia (18000 > 0) is filtered out.

Constraints

  • 0 <= len(people) <= 200,000
  • age, salary, and integer bounds fit within signed 64-bit integers (-2^63 through 2^63 - 1).
  • Whenever both bounds of a pair are non-None, min_age <= max_age and min_salary <= max_salary.
  • Occupation and name strings use exact case-sensitive matching.

Step-by-step walkthrough

  1. Understand the filter rules and guarantees

    We are given people (up to 200,000 dictionaries with keys first_name, last_name, age, occupation, salary) alongside five optional filter parameters:

    • min_age / max_age: inclusive lower and upper bounds on age (min_age <= age <= max_age).
    • occupations: allowed occupation strings using exact case-sensitive matching.
    • min_salary / max_salary: inclusive lower and upper bounds on salary (min_salary <= salary <= max_salary).

    Every contract detail matters:

    • AND semantics: A person matches only when they pass every non-None check.
    • Independent None toggles: Passing None turns off only that single bound or check (min_age = 28, max_age = None enforces age >= 28 with no upper cap).
    • Order preservation & immutability: Always return a fresh list preserving relative order from people, without mutating people, any person dictionary, or occupations.
  2. Why converting occupations into a set avoids a hidden O(n * m) bottleneck

    Because we must keep input order and inspect each record at least once, a single left-to-right scan over people is optimal — provided every per-record check runs in O(1) time!

    Look closely at occupations: Optional[List[str]]. When occupations holds m = 1,000 strings and people holds n = 200,000 records, evaluating person["occupation"] in occupations directly on the list scans up to 1,000 strings per person:

    Direct list scan (`in occupations`):
      200,000 people * up to 1,000 list comparisons each = 200,000,000 string checks  --> O(n * m)
    
    Upfront hash-set conversion (`allowed_occupations = set(occupations)`):
      Build set once: 1,000 hashes  +  200,000 people * O(1) hash lookup = ~201,000 ops --> O(n + m)
    

    Building set(occupations) once before the loop keeps total runtime linear in O(n + m) and leaves the caller's occupations list untouched.

  3. Key trap: test is not None explicitly, never truthiness

    In Python, writing if max_salary and salary > max_salary: fails whenever a bound equals 0 because 0 is falsy (bool(0) == False), as seen in Example 3:

    Suppose Pia has salary = 18000 and the caller passes max_salary = 0:
    
      BUGGY (`if max_salary and ...`):   bool(0) is False -> cap is skipped! (18000 is wrongly kept)
      RIGHT (`if max_salary is not None and ...`): 0 is not None is True -> 18000 > 0 rejects Pia!
    

    Ages and salaries span signed 64-bit integers (-2^63 through 2^63 - 1), so 0 and negative bounds are valid active filters. Always compare bound is not None. (And since Python integers have arbitrary precision, 64-bit boundary comparisons never overflow.)

  4. Write the per-person predicate and main filter loop

    Isolating the five checks in a small helper matches_criteria keeps each gate clear:

    • Reject age < min_age or age > max_age so exact endpoint ties (age == min_age or age == max_age) evaluate to True (inclusive bounds).
    • In filter_people, always construct a brand-new matched_people = [] list — even when all five filters are None — so the caller never receives an alias to people.
    from typing import Any, Dict, List, Optional, Set
    
    
    def matches_criteria(
        person: Dict[str, Any],
        min_age: Optional[int],
        max_age: Optional[int],
        allowed_occupations: Optional[Set[str]],
        min_salary: Optional[int],
        max_salary: Optional[int],
    ) -> bool:
        """Return True if `person` satisfies every filter that is not None."""
        age = person["age"]
        salary = person["salary"]
    
        if min_age is not None and age < min_age:
            return False
        if max_age is not None and age > max_age:
            return False
        if allowed_occupations is not None and person["occupation"] not in allowed_occupations:
            return False
        if min_salary is not None and salary < min_salary:
            return False
        if max_salary is not None and salary > max_salary:
            return False
    
        return True
    
    
    def filter_people(people: List[Dict[str, object]], min_age: Optional[int], max_age: Optional[int], occupations: Optional[List[str]], min_salary: Optional[int], max_salary: Optional[int]) -> List[Dict[str, object]]:
        allowed_occupations: Optional[Set[str]] = None
        if occupations is not None:
            allowed_occupations = set(occupations)
    
        matched_people: List[Dict[str, object]] = []
        for person in people:
            if matches_criteria(person, min_age, max_age, allowed_occupations, min_salary, max_salary):
                matched_people.append(person)
    
        return matched_people
    
  5. Trace through Example 1 and boundary cases

    Let's walk Example 1 with min_age = 28, max_age = 40, allowed_occupations = {"analyst", "nurse"}, min_salary = 85000, max_salary = None:

    Gate 1: age >= 28   Gate 2: age <= 40   Gate 3: occ in set   Gate 4: sal >= 85000   Gate 5: open (None)
    -------------------------------------------------------------------------------------------------------
    Leo  (24, "analyst",   92000) -> Gate 1 FAILS (24 < 28)  -> returns False immediately
    Nora (31, "nurse",     88000) -> Gates 1..5 all pass     -> appended to matched_people!
    Omar (38, "analyst",   76000) -> Gates 1..3 pass -> Gate 4 FAILS (76000 < 85000) -> False
    Zoe  (44, "therapist", 91000) -> Gate 2 FAILS (44 > 40)  -> returns False immediately
    Eli  (29, "nurse",     95000) -> Gates 1..5 all pass     -> appended to matched_people!
    
    Result: [Nora, Eli]
    

    And in Example 2 (age = 26 with 26..26, "Pharmacist" vs "pharmacist", salary = 115000 with 115000..115000), Maya clears every exact inclusive bound while Dan fails case-sensitive set membership on Gate 3.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def matches_criteria(
        person: Dict[str, Any],
        min_age: Optional[int],
        max_age: Optional[int],
        allowed_occupations: Optional[Set[str]],
        min_salary: Optional[int],
        max_salary: Optional[int],
    ) -> bool:
        """Return True if `person` satisfies every filter that is not None."""
        age = person["age"]
        salary = person["salary"]
    
        # Check `is not None` explicitly: 0 and negative ints are active bounds, not "disabled".
        # Rejecting only `< min` and `> max` keeps boundary ties (`==`), making ranges inclusive.
        if min_age is not None and age < min_age:
            return False
        if max_age is not None and age > max_age:
            return False
        if allowed_occupations is not None and person["occupation"] not in allowed_occupations:
            return False
        if min_salary is not None and salary < min_salary:
            return False
        if max_salary is not None and salary > max_salary:
            return False
    
        return True
    
    
    def filter_people(people: List[Dict[str, object]], min_age: Optional[int], max_age: Optional[int], occupations: Optional[List[str]], min_salary: Optional[int], max_salary: Optional[int]) -> List[Dict[str, object]]:
        # allowed_occupations: set of case-sensitive strings, e.g. {"analyst", "nurse"},
        # or None when disabled. Building a set once makes each membership check O(1) instead of O(m).
        allowed_occupations: Optional[Set[str]] = None
        if occupations is not None:
            allowed_occupations = set(occupations)
    
        # Always build a fresh list so input order is preserved and `people` is never aliased or mutated.
        matched_people: List[Dict[str, object]] = []
        for person in people:
            if matches_criteria(person, min_age, max_age, allowed_occupations, min_salary, max_salary):
                matched_people.append(person)
    
        return matched_people
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of filter_people like a single-file corridor with five optional checkpoints (min_age, max_age, occupations, min_salary, max_salary): whenever a checkpoint's parameter is None, its gate stands wide open; otherwise, a record must clear every active gate to enter the output list in the exact order it arrived (stable filtering, meaning the relative order of kept records never changes). Before scanning people, we convert occupations into a hash set (set(occupations), a hash-table container that checks string membership in constant O(1) average time rather than scanning the list end to end). Inside matches_criteria, each gate relies on short-circuit evaluation (returning False on the first failed check without testing remaining gates).

Why do rushed implementations stumble here? Testing person["occupation"] in occupations directly on a list scans all m allowed roles for each of the n people, inflating runtime from linear to O(n * m) (200,000,000 string comparisons when n = 200,000 and m = 1,000). Worse, writing if max_salary: instead of if max_salary is not None: silently disables a bound of 0 because 0 is falsy in Python, and returning people directly as a shortcut when every parameter is None hands back an alias to the caller's own list instead of allocating a fresh list!

Here is how Example 1 flows through the five checkpoints (age in [28, 40], occupation in {"analyst", "nurse"}, salary >= 85000, max_salary disabled):

Person                           [age>=28]  [age<=40]  [occ in set]  [sal>=85k]  [max_sal=None]
-----------------------------------------------------------------------------------------------
Leo  (24, "analyst",   92000)      FAIL  --> dropped immediately
Nora (31, "nurse",     88000)      pass       pass        pass          pass         open --> KEPT
Omar (38, "analyst",   76000)      pass       pass        pass          FAIL   --> dropped
Zoe  (44, "therapist", 91000)      pass       FAIL  --> dropped immediately
Eli  (29, "nurse",     95000)      pass       pass        pass          pass         open --> KEPT

Complexity

Let n be len(people), m be len(occupations) (0 when occupations is None), and k (k <= n) be the number of matched records returned.

  • Time: O(n + m) average. Constructing allowed_occupations = set(occupations) hashes m strings once in O(m) average time; then scanning people visits each of the n dictionaries once, performing at most four O(1) integer comparisons and one O(1) average set lookup per dictionary.
  • Space: O(m + k). allowed_occupations holds up to m distinct role strings, and matched_people holds k dictionary references (referencing existing person dictionaries without mutating or deep-copying them).

Edge cases

  • Empty people list ([]): The loop executes zero iterations and returns a new empty list [].
  • All five parameters None: Every record matches and is appended into a fresh list (got == people is True, while got is people is False).
  • Exact endpoint ties (min_age == age == max_age) (Example 2): Kept, since both < min and > max evaluate to False on equality.
  • Zero or negative bounds (max_salary = 0, min_salary = 0) (Example 3): Enforced as real numeric bounds because every check compares explicitly with None.
  • One-sided bounds (min_age = 18, max_age = None): Applies age >= 18 while leaving the upper side unbounded.
  • Case-sensitive occupations (Example 2): "Pharmacist" matches "Pharmacist" only, rejecting "pharmacist" and "PHARMACIST".
  • Signed 64-bit integer limits (-2^63 and 2^63 - 1): Python's arbitrary-precision integers compare exact 64-bit extremes without overflow or floating-point rounding (float(2**63 - 1) rounds to 2**63!).
  • Duplicate entries in occupations: Collapsed automatically by set(occupations).

Common mistakes

  • Truthiness checks (if max_salary:) instead of if max_salary is not None:: Silently drops 0 bounds (and would misread an empty occupations = [] list as "unfiltered" rather than "match nothing").
  • Membership checks on the raw list (person["occupation"] in occupations): Triggers O(n * m) slowdown when both people and occupations are large.
  • Strict inequalities (<= / >= when rejecting, keeping only min < val < max): Incorrectly drops records sitting directly on a boundary value.
  • Case folding with .lower(): Violates case-sensitive occupation matching.
  • Shortcut return people when all filters are None: Breaks the fresh-list guarantee so later caller edits to the result would mutate people.
  • Casting bounds or values to float to use float("-inf") / float("inf"): Converting huge 64-bit integers via float(...) loses precision near 2^63 - 1; explicit is not None integer checks avoid floats altogether.

Follow-up questions

  • How would you accelerate repeated filter queries when the underlying list of people rarely changes? Precompute in-memory indexes once: an inverted map indices_by_occupation[occ] holding sorted record indices per role, plus sorted (age, idx) and (salary, idx) arrays for binary-search range slicing (bisect). At query time, start from whichever active filter yields the smallest candidate slice, verify the remaining predicates on those candidates, and sort surviving idx values to preserve original list order (or index (age, salary) pairs in a k-d tree — a binary space-partitioning tree that alternates splits across dimensions — for fast two-dimensional range lookups).
  • How could you refactor the function signature so adding ten more optional filter attributes stays clean and fast? Replace long positional parameter lists with a typed PersonFilter dataclass or a list of declarative predicate specs — such as RangeRule(field, min_val, max_val) and SetRule(field, allowed_values) — compiled into a compact list of active checks once before looping over people. Adding department, location, or years_experience then leaves the function signature unchanged and skips disabled checks completely inside the inner loop.
  • What strategy should a production service use when incoming person dictionaries have missing keys or invalid field types? Define an explicit validation boundary up front: synchronous request APIs should validate payloads with typed schemas (such as Pydantic) and raise a descriptive ValueError pointing to the offending record index and field name, whereas batch ingestion pipelines handling noisy external feeds should route malformed records to a dead-letter queue with structured error counts rather than crashing mid-batch with KeyError/TypeError or silently discarding bad rows.

Follow-up questions

Similar questions

More Commure interview questions

All 3 Commure questions →