Find Extreme Dictionary by Dynamic Key
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement select_by_field, which scans a list of semi-structured dictionaries (records) and returns the dictionary holding the minimum or maximum integer value for a requested key field.
Each entry in records maps string keys to integer values, and individual entries may omit field altogether. Enforce all five rules below:
- Mode validation:
modedefaults to"MAX"and accepts"MIN"or"MAX"regardless of letter case (such as"min"or"Max"). Ifmodeis not a string or its uppercase value is neither"MIN"nor"MAX", raiseValueError—even whenrecordsis empty. - Missing-key filtering: Ignore every dictionary where
fieldis absent (fieldmapped to0counts as present). - Extreme selection: Among dictionaries containing
field, choose the dictionary whoserecord[field]is smallest whenmodeis"MIN"or largest whenmodeis"MAX", returning the original dictionary object itself rather than a copy. - Earliest tie-breaking: Whenever multiple dictionaries share the winning value for
field, return the one that appears earliest inrecords. - Empty match: Return
Nonewhenrecordsis empty or when no dictionary containsfield.
def select_by_field(
records: list[dict[str, int]],
field: str,
mode: str = "MAX",
) -> dict[str, int] | None:
pass
Examples
Example 1
Input:
records = [
{"cpu": 85, "host": 1},
{"cpu": 40, "mem": 64},
{"cpu": 85, "host": 2}
]
field = "cpu"
mode = "MAX"
Output:
{"cpu": 85, "host": 1}
Explanation: Both "host": 1 (index 0) and "host": 2 (index 2) share the maximum "cpu" value of 85. Tie-breaking keeps the earlier entry at index 0.
Example 2
Input:
records = [
{"node": 10, "delta": -4},
{"node": 11},
{"node": 12, "delta": -15},
{"node": 13, "delta": 0}
]
field = "delta"
mode = "MIN"
Output:
{"node": 12, "delta": -15}
Explanation: "node": 11 lacks "delta" and is skipped. Among the remaining values [-4, -15, 0], the minimum is -15 at "node": 12.
Example 3
Input:
records = [{"port": 80}, {"port": 443, "tls": 1}]
field = "latency"
mode = "MAX"
Output:
None
Explanation: Neither dictionary contains "latency", so select_by_field returns None.
Constraints
0 <= len(records) <= 10^50 <= len(record) <= 50for every dictionary inrecords-10^9 <= value <= 10^9for every stored integer- Target
O(N)time andO(1)auxiliary memory, whereN = len(records).
Step-by-step walkthrough
Understand the rules and semi-structured inputs
We are given a list of dictionaries (
records), a dynamic key name (field), andmode("MIN"or"MAX", case-insensitive, defaulting to"MAX"). Because the input is semi-structured (each dictionary can hold a different subset of keys), not every dictionary containsfield:records: index 0: {"node": 10, "delta": -4} ──► has "delta" (-4) index 1: {"node": 11} ──► missing "delta" (skip!) index 2: {"node": 12, "delta": -15} ──► has "delta" (-15) ◄── MIN winner index 3: {"node": 13, "delta": 0} ──► has "delta" (0)Every edge case is pinned down by five rules:
- Ignore records missing
field. - Pick the extreme (
MINorMAX) among records that actually containfield. - Break ties by earliest occurrence: if two records share the winning value, return the one that appeared first in
records(the exact dictionary object itself, not a copy). - Return
Noneifrecordsis empty or if zero records containfield. - Raise
ValueErrorifmode(ignoring letter case) is anything other than"MIN"or"MAX".
- Ignore records missing
Why filtering and sorting does too much work
A tempting first try is to filter
valid = [r for r in records if field in r], sortvalidbyr[field], and grab one end of the sorted list. That runs into three problems:- Extra memory (
O(N)instead ofO(1)): buildingvalidcopies up to100,000dictionary references. - Extra time (
O(N log N)instead ofO(N)): sorting orders allNitems when we only care about the single extreme item. - A sneaky tie-breaker bug for
MAX: Python'ssort()is stable (tied items stay in their original left-to-right order), sosorted_valid[0]is indeed the first minimum—butsorted_valid[-1]is the last maximum!
Scanning the list once and remembering only the best record seen so far avoids all three problems.
- Extra memory (
Key idea: single-pass scan with strict tie-breaking
We walk
recordsfrom left to right keeping just two variables:best_recordandbest_value, both initialized toNone.Three defensive details make the scan rock-solid:
- Test membership with
field not in record, neverif not record.get(field):. In Python,0is falsy (bool(0) == False), so a truthiness check onrecord.get(field)would accidentally skip valid records like{"delta": 0}! - Seed from the first matching record (
best_record is None). Initializingbest_value = 0would break whenevermode == "MAX"and all values are negative (such as[-5, -3, -10]). Initializing toNoneadopts the first valid record unconditionally, without mixing floats likefloat("-inf")into integer logic. - Use strict inequality (
>forMAX,<forMIN). When a later record hasvalue == best_value, bothvalue > best_valueandvalue < best_valueevaluate toFalse, so the earlierbest_recordstays in place automatically.
- Test membership with
Validate `mode` before touching `records`
What should happen on
select_by_field([], "cpu", mode="AVG")—should it returnNone(empty list) or raiseValueError(invalid mode)? Passing"AVG"is always a caller bug regardless of whether today's batch of records happens to be empty, so we validatemodefirst, before entering the loop. Checkingisinstance(mode, str)first also ensures passingmode=NoneraisesValueErrorrather than crashing withAttributeErroron.upper().# Phase 1: validate `mode` up front so invalid modes raise ValueError even when `records` is empty. if not isinstance(mode, str): raise ValueError(f"mode must be 'MIN' or 'MAX', got {mode!r}") normalized_mode = mode.upper() if normalized_mode not in ("MIN", "MAX"): raise ValueError(f"mode must be 'MIN' or 'MAX', got {mode!r}") want_max = normalized_mode == "MAX"Trace Example 1 and Example 2 step by step
First, trace Example 1 (
field = "cpu",mode = "MAX") to see tie-breaking in action:Index Record "cpu" in record? Comparison vs best_value Winner after step ───── ────────────────────── ──────────────── ──────────────────────── ──────────────────────────── 0 {"cpu": 85, "host": 1} Yes (85) first match -> True index 0 (best_value = 85) 1 {"cpu": 40, "mem": 64} Yes (40) 40 > 85 is False index 0 (best_value = 85) 2 {"cpu": 85, "host": 2} Yes (85) 85 > 85 is False (tie!) index 0 (best_value = 85)Index
0({"cpu": 85, "host": 1}) wins the tie because85 > 85isFalse.Next, trace Example 2 (
field = "delta",mode = "MIN") to see missing keys and0handled cleanly:Index Record "delta" in record? Comparison vs best_value Winner after step ───── ───────────────────────── ────────────────── ──────────────────────── ──────────────────────────── 0 {"node": 10, "delta": -4} Yes (-4) first match -> True node 10 (best_value = -4) 1 {"node": 11} No (skip) — node 10 (best_value = -4) 2 {"node": 12, "delta": -15} Yes (-15) -15 < -4 is True node 12 (best_value = -15) 3 {"node": 13, "delta": 0} Yes (0) 0 < -15 is False node 12 (best_value = -15)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def select_by_field( records: list[dict[str, int]], field: str, mode: str = "MAX", ) -> dict[str, int] | None: # Phase 1: validate `mode` up front so invalid modes raise ValueError even when `records` is empty. if not isinstance(mode, str): raise ValueError(f"mode must be 'MIN' or 'MAX', got {mode!r}") normalized_mode = mode.upper() if normalized_mode not in ("MIN", "MAX"): raise ValueError(f"mode must be 'MIN' or 'MAX', got {mode!r}") want_max = normalized_mode == "MAX" # Phase 2: scan once, tracking the winning record dict and its integer value for `field`. # Starting at None avoids fake numeric sentinels (like 0, which fails on all-negative MAX). best_record: dict[str, int] | None = None best_value: int | None = None for record in records: # Check key membership with `in` (not `record.get(field)`), because 0 is falsy yet valid. if field not in record: continue value = record[field] if best_record is None or best_value is None: is_better = True elif want_max: # Strict `>` keeps the earlier record whenever a later record ties `best_value`. is_better = value > best_value else: # Strict `<` keeps the earlier record whenever a later record ties `best_value`. is_better = value < best_value if is_better: best_record = record best_value = value return best_record✅ Submit now — all tests should pass.
Intuition & how it works
Think of scanning records like a single-elimination championship belt: you walk down a line of contestants once from left to right. Contestants who do not compete in the requested event (field is absent from their dictionary—typical in semi-structured data, where entries do not all carry the exact same keys) simply step aside. The very first valid contestant automatically claims the belt (best_record), and every valid contestant after that takes the belt only if their score strictly beats the current champion (> for "MAX", < for "MIN"). Because a tie never unseats the current holder, the earliest tied entry naturally retains the belt.
Why not filter the list and sort it? Filtering builds an O(N) temporary list and sorting takes O(N log N) time, whereas one left-to-right pass finds the winner in O(N) time and O(1) extra space. Worse, sorting hides a classic tie-breaker bug: Python uses a stable sort (a sort that preserves the original left-to-right order of equal elements), so taking the last element sorted_records[-1] for "MAX" actually returns the last tied dictionary instead of the first!
Let's trace Example 1 on records = [{"cpu": 85, "host": 1}, {"cpu": 40, "mem": 64}, {"cpu": 85, "host": 2}] with field = "cpu", mode = "MAX":
1. {"cpu": 85, "host": 1} -> first match! -> best_record = host 1, best_value = 85
2. {"cpu": 40, "mem": 64} -> 40 > 85 is False -> host 1 stays in the lead
3. {"cpu": 85, "host": 2} -> 85 > 85 is False -> tie! host 1 keeps the lead -> return host 1
Complexity
Let N be len(records).
- Time:
O(N)average time. We validatemodeinO(1)time, then visit each of theNdictionaries once. Each step performs anO(1)average hash-table key lookup (field not in record), at most oneO(1)read (record[field]), and one integer comparison—independent of how many other keys each dictionary holds. - Space:
O(1)auxiliary space. Regardless of how largeNgrows, we store only a handful of local variables (normalized_mode,want_max,best_record,best_value,value,is_better) and return a reference to the existing winning dictionary without copying anything.
Edge cases
- Empty
recordslist ([]) orfieldmissing from every record:best_recordstarts atNoneand is never updated, returningNonecleanly without special-case branches. - Field value equal to
0: In Python,0is a falsy value (a value that evaluates toFalsein anifcondition), soif record.get(field):would wrongly skip{"delta": 0}. Checkingif field not in record:tests key presence directly. - All values negative under
"MAX"(or all positive under"MIN"): Initializingbest_record = Noneinstead of a numeric sentinel value (a dummy starting number such as0) ensures[{"t": -5}, {"t": -3}]returns{"t": -3}rather than losing to0. - Ties on distinct dictionary objects: Strict
</>guarantees the earliest dictionary object itself (got is first) is returned, not a later record with the same field value. - Case-insensitive
mode("min","Max","mAx"): Normalized once viamode.upper(). - Invalid
modeon an empty list (or non-stringmodelikeNone): Because validation runs before the loop and checksisinstance(mode, str),select_by_field([], "cpu", "AVG")andselect_by_field([], "cpu", None)both raiseValueError.
Common mistakes
- Writing
if record.get(field):instead ofif field in record:: Silently ignores every record whererecord[field] == 0. - Initializing
best_value = 0: Fails whenever"MAX"sees only negative integers or"MIN"sees only positive integers. - Using
>=or<=instead of>or<: Overwritesbest_recordon ties, returning the last occurrence instead of the first. - Validating
modeinside the loop: ReturnsNoneinstead of raisingValueErrorwhenrecordsis empty or no record containsfield. - Returning
dict(best_record)(a shallow copy): Wastes time/memory and breaks callers that check object identity (is).
Alternative approaches
- Generator expression with Python's built-in
min/max: Python'sminandmaxguarantee that when multiple items tie for the extreme key, the first item encountered is returned. After validatingmode,candidates = (r for r in records if field in r)passed tomax(candidates, key=lambda r: r[field], default=None)(ormin(...)) achieves the sameO(N)time andO(1)space. Writing the explicit loop is easier to read step by step, avoids per-elementlambdacall overhead, and extends naturally to multi-field tie-breakers.
Follow-up questions
- What changes are needed so the function can consume a lazy one-pass iterable or live event stream in constant memory? Because our loop visits one dictionary at a time in forward order without calling
len(records)or indexing by position, the implementation already works unchanged on any single-passIterable[dict[str, int]]—simply broaden the parameter type hint fromlist[...]toIterable[...]. Keepingmodevalidation ahead of the loop guarantees invalid modes fail before consuming a single element. Auxiliary memory remainsO(1)(holding onlybest_record), and for an unending live stream you would expose the running champion on demand or emit winners per fixed time window. - How would you extend the API to break ties using a prioritized list of fallback keys and directions? Accept an ordered list of
(key_name, direction)pairs—such as[("cpu", "MAX"), ("mem", "MIN")]—and write a helperbeats_champion(candidate, champion, rules)that walks the rules in order: at the first rule wherecandidateandchampiondiffer (defining an explicit policy if a fallback key is missing, such as present outranking missing), returncand_val > champ_valfor"MAX"orcand_val < champ_valfor"MIN". If every rule ties, returnFalseso the earlier dictionary still wins, keeping runtimeO(N * K)forKrules and extra spaceO(1). - Suppose the dataset never changes and callers run millions of lookups across varying keys—how would you index the data for fast queries? When every lookup spans the entire immutable dataset and varies only
(field, mode), scan all records once at startup (O(total key-value entries), at most50 * Nhere) to populate a dictionaryextremes[field] = (min_record, max_record); each subsequent lookup then finishes inO(1)time! If callers also restrict lookups to an index slice[L, R]ofrecords, store perfieldthe sorted list of(index, value)pairs wherefieldappears, augmented with a sparse table (a precomputed table over power-of-two interval lengths that answers range min/max queries inO(1)time usingO(N log N)space) or a segment tree (a binary tree over intervals that answers range min/max queries inO(log N)time inO(N)space and also supportsO(log N)updates), breaking value ties toward the smallerindex.
Follow-up questions
- What changes are needed so the function can consume a lazy one-pass iterable or live event stream in constant memory?
- How would you extend the API to break ties using a prioritized list of fallback keys and directions?
- Suppose the dataset never changes and callers run millions of lookups across varying keys—how would you index the data for fast queries?
Similar questions
- Fixed-Stride Stream Iterator
- Sparse Minesweeper Engine and Flood-Fill Optimization
- Email and Password Authentication Service
- Canonical Unix Path and Lazy Nested-List Iterator
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target