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:

  1. Mode validation: mode defaults to "MAX" and accepts "MIN" or "MAX" regardless of letter case (such as "min" or "Max"). If mode is not a string or its uppercase value is neither "MIN" nor "MAX", raise ValueError—even when records is empty.
  2. Missing-key filtering: Ignore every dictionary where field is absent (field mapped to 0 counts as present).
  3. Extreme selection: Among dictionaries containing field, choose the dictionary whose record[field] is smallest when mode is "MIN" or largest when mode is "MAX", returning the original dictionary object itself rather than a copy.
  4. Earliest tie-breaking: Whenever multiple dictionaries share the winning value for field, return the one that appears earliest in records.
  5. Empty match: Return None when records is empty or when no dictionary contains field.
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^5
  • 0 <= len(record) <= 50 for every dictionary in records
  • -10^9 <= value <= 10^9 for every stored integer
  • Target O(N) time and O(1) auxiliary memory, where N = len(records).

Step-by-step walkthrough

  1. Understand the rules and semi-structured inputs

    We are given a list of dictionaries (records), a dynamic key name (field), and mode ("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 contains field:

    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:

    1. Ignore records missing field.
    2. Pick the extreme (MIN or MAX) among records that actually contain field.
    3. 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).
    4. Return None if records is empty or if zero records contain field.
    5. Raise ValueError if mode (ignoring letter case) is anything other than "MIN" or "MAX".
  2. 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], sort valid by r[field], and grab one end of the sorted list. That runs into three problems:

    • Extra memory (O(N) instead of O(1)): building valid copies up to 100,000 dictionary references.
    • Extra time (O(N log N) instead of O(N)): sorting orders all N items when we only care about the single extreme item.
    • A sneaky tie-breaker bug for MAX: Python's sort() is stable (tied items stay in their original left-to-right order), so sorted_valid[0] is indeed the first minimum—but sorted_valid[-1] is the last maximum!

    Scanning the list once and remembering only the best record seen so far avoids all three problems.

  3. Key idea: single-pass scan with strict tie-breaking

    We walk records from left to right keeping just two variables: best_record and best_value, both initialized to None.

    Three defensive details make the scan rock-solid:

    • Test membership with field not in record, never if not record.get(field):. In Python, 0 is falsy (bool(0) == False), so a truthiness check on record.get(field) would accidentally skip valid records like {"delta": 0}!
    • Seed from the first matching record (best_record is None). Initializing best_value = 0 would break whenever mode == "MAX" and all values are negative (such as [-5, -3, -10]). Initializing to None adopts the first valid record unconditionally, without mixing floats like float("-inf") into integer logic.
    • Use strict inequality (> for MAX, < for MIN). When a later record has value == best_value, both value > best_value and value < best_value evaluate to False, so the earlier best_record stays in place automatically.
  4. Validate `mode` before touching `records`

    What should happen on select_by_field([], "cpu", mode="AVG")—should it return None (empty list) or raise ValueError (invalid mode)? Passing "AVG" is always a caller bug regardless of whether today's batch of records happens to be empty, so we validate mode first, before entering the loop. Checking isinstance(mode, str) first also ensures passing mode=None raises ValueError rather than crashing with AttributeError on .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"
    
  5. 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 because 85 > 85 is False.

    Next, trace Example 2 (field = "delta", mode = "MIN") to see missing keys and 0 handled 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)
    
  6. 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 validate mode in O(1) time, then visit each of the N dictionaries once. Each step performs an O(1) average hash-table key lookup (field not in record), at most one O(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 large N grows, 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 records list ([]) or field missing from every record: best_record starts at None and is never updated, returning None cleanly without special-case branches.
  • Field value equal to 0: In Python, 0 is a falsy value (a value that evaluates to False in an if condition), so if record.get(field): would wrongly skip {"delta": 0}. Checking if field not in record: tests key presence directly.
  • All values negative under "MAX" (or all positive under "MIN"): Initializing best_record = None instead of a numeric sentinel value (a dummy starting number such as 0) ensures [{"t": -5}, {"t": -3}] returns {"t": -3} rather than losing to 0.
  • 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 via mode.upper().
  • Invalid mode on an empty list (or non-string mode like None): Because validation runs before the loop and checks isinstance(mode, str), select_by_field([], "cpu", "AVG") and select_by_field([], "cpu", None) both raise ValueError.

Common mistakes

  • Writing if record.get(field): instead of if field in record:: Silently ignores every record where record[field] == 0.
  • Initializing best_value = 0: Fails whenever "MAX" sees only negative integers or "MIN" sees only positive integers.
  • Using >= or <= instead of > or <: Overwrites best_record on ties, returning the last occurrence instead of the first.
  • Validating mode inside the loop: Returns None instead of raising ValueError when records is empty or no record contains field.
  • 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's min and max guarantee that when multiple items tie for the extreme key, the first item encountered is returned. After validating mode, candidates = (r for r in records if field in r) passed to max(candidates, key=lambda r: r[field], default=None) (or min(...)) achieves the same O(N) time and O(1) space. Writing the explicit loop is easier to read step by step, avoids per-element lambda call 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-pass Iterable[dict[str, int]]—simply broaden the parameter type hint from list[...] to Iterable[...]. Keeping mode validation ahead of the loop guarantees invalid modes fail before consuming a single element. Auxiliary memory remains O(1) (holding only best_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 helper beats_champion(candidate, champion, rules) that walks the rules in order: at the first rule where candidate and champion differ (defining an explicit policy if a fallback key is missing, such as present outranking missing), return cand_val > champ_val for "MAX" or cand_val < champ_val for "MIN". If every rule ties, return False so the earlier dictionary still wins, keeping runtime O(N * K) for K rules and extra space O(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 most 50 * N here) to populate a dictionary extremes[field] = (min_record, max_record); each subsequent lookup then finishes in O(1) time! If callers also restrict lookups to an index slice [L, R] of records, store per field the sorted list of (index, value) pairs where field appears, augmented with a sparse table (a precomputed table over power-of-two interval lengths that answers range min/max queries in O(1) time using O(N log N) space) or a segment tree (a binary tree over intervals that answers range min/max queries in O(log N) time in O(N) space and also supports O(log N) updates), breaking value ties toward the smaller index.

Follow-up questions

Similar questions

More Bridge interview questions

All 5 Bridge questions →