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,000age,salary, and integer bounds fit within signed 64-bit integers (-2^63through2^63 - 1).- Whenever both bounds of a pair are non-
None,min_age <= max_ageandmin_salary <= max_salary. - Occupation and name strings use exact case-sensitive matching.
Step-by-step walkthrough
Understand the filter rules and guarantees
We are given
people(up to200,000dictionaries with keysfirst_name,last_name,age,occupation,salary) alongside five optional filter parameters:min_age/max_age: inclusive lower and upper bounds onage(min_age <= age <= max_age).occupations: allowed occupation strings using exact case-sensitive matching.min_salary/max_salary: inclusive lower and upper bounds onsalary(min_salary <= salary <= max_salary).
Every contract detail matters:
- AND semantics: A person matches only when they pass every non-
Nonecheck. - Independent
Nonetoggles: PassingNoneturns off only that single bound or check (min_age = 28, max_age = Noneenforcesage >= 28with no upper cap). - Order preservation & immutability: Always return a fresh list preserving relative order from
people, without mutatingpeople, any person dictionary, oroccupations.
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
peopleis optimal — provided every per-record check runs inO(1)time!Look closely at
occupations: Optional[List[str]]. Whenoccupationsholdsm = 1,000strings andpeopleholdsn = 200,000records, evaluatingperson["occupation"] in occupationsdirectly on the list scans up to1,000strings 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 inO(n + m)and leaves the caller'soccupationslist untouched.Key trap: test is not None explicitly, never truthiness
In Python, writing
if max_salary and salary > max_salary:fails whenever a bound equals0because0is 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^63through2^63 - 1), so0and negative bounds are valid active filters. Always comparebound is not None. (And since Python integers have arbitrary precision, 64-bit boundary comparisons never overflow.)Write the per-person predicate and main filter loop
Isolating the five checks in a small helper
matches_criteriakeeps each gate clear:- Reject
age < min_ageorage > max_ageso exact endpoint ties (age == min_ageorage == max_age) evaluate toTrue(inclusive bounds). - In
filter_people, always construct a brand-newmatched_people = []list — even when all five filters areNone— so the caller never receives an alias topeople.
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- Reject
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 = 26with26..26,"Pharmacist"vs"pharmacist",salary = 115000with115000..115000),Mayaclears every exact inclusive bound whileDanfails case-sensitive set membership on Gate 3.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. Constructingallowed_occupations = set(occupations)hashesmstrings once inO(m)average time; then scanningpeoplevisits each of thendictionaries once, performing at most fourO(1)integer comparisons and oneO(1)average set lookup per dictionary. - Space:
O(m + k).allowed_occupationsholds up tomdistinct role strings, andmatched_peopleholdskdictionary references (referencing existing person dictionaries without mutating or deep-copying them).
Edge cases
- Empty
peoplelist ([]): 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 == peopleisTrue, whilegot is peopleisFalse). - Exact endpoint ties (
min_age == age == max_age) (Example 2): Kept, since both< minand> maxevaluate toFalseon equality. - Zero or negative bounds (
max_salary = 0,min_salary = 0) (Example 3): Enforced as real numeric bounds because every check compares explicitly withNone. - One-sided bounds (
min_age = 18, max_age = None): Appliesage >= 18while leaving the upper side unbounded. - Case-sensitive occupations (Example 2):
"Pharmacist"matches"Pharmacist"only, rejecting"pharmacist"and"PHARMACIST". - Signed 64-bit integer limits (
-2^63and2^63 - 1): Python's arbitrary-precision integers compare exact 64-bit extremes without overflow or floating-point rounding (float(2**63 - 1)rounds to2**63!). - Duplicate entries in
occupations: Collapsed automatically byset(occupations).
Common mistakes
- Truthiness checks (
if max_salary:) instead ofif max_salary is not None:: Silently drops0bounds (and would misread an emptyoccupations = []list as "unfiltered" rather than "match nothing"). - Membership checks on the raw
list(person["occupation"] in occupations): TriggersO(n * m)slowdown when bothpeopleandoccupationsare large. - Strict inequalities (
<=/>=when rejecting, keeping onlymin < val < max): Incorrectly drops records sitting directly on a boundary value. - Case folding with
.lower(): Violates case-sensitive occupation matching. - Shortcut
return peoplewhen all filters areNone: Breaks the fresh-list guarantee so later caller edits to the result would mutatepeople. - Casting bounds or values to
floatto usefloat("-inf")/float("inf"): Converting huge 64-bit integers viafloat(...)loses precision near2^63 - 1; explicitis not Noneinteger 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 survivingidxvalues 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
PersonFilterdataclass or a list of declarative predicate specs — such asRangeRule(field, min_val, max_val)andSetRule(field, allowed_values)— compiled into a compact list of active checks once before looping overpeople. Addingdepartment,location, oryears_experiencethen 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
ValueErrorpointing 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 withKeyError/TypeErroror silently discarding bad rows.
Follow-up questions
- How would you accelerate repeated filter queries when the underlying list of people rarely changes?
- How could you refactor the function signature so adding ten more optional filter attributes stays clean and fast?
- What strategy should a production service use when incoming person dictionaries have missing keys or invalid field types?
Similar questions
- Monthly Creator Royalty Calculation and Payouts
- Career Intro, Technical Deep Dive, and AI-Coding Boundaries
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance