Find Dictionary with Extreme Field Value
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests your ability to scan a collection of sparse dictionaries and retrieve the one with the minimum or maximum value for a specified field.
Problem Statement
Write a function that searches through a list of dictionaries and returns the dictionary containing either the smallest or largest value for a given field name.
Each dictionary maps string keys to integer values. The dictionaries may have different keys—not all of them will contain the field you're searching for.
Your function must:
- Consider only dictionaries that actually contain the specified
field. - Return the dictionary whose value for
fieldis the minimum or maximum, based on themodeparameter. - When multiple dictionaries share the same extreme value, return the one that appears first in the list.
- Return
Noneif the input list is empty or if no dictionary contains the specified field. - Raise a
ValueErrorifmodeis anything other than"MIN"or"MAX"(comparison should be case-insensitive).
Function Signature
def find_extreme_record(
records: list[dict[str, int]],
field: str,
mode: str = "MAX"
) -> dict[str, int] | None:
pass
Constraints
0 <= len(records) <= 100,000- Each dictionary contains at most 50 key-value pairs
- Integer values range from
-10^9to10^9 - Your solution should run in O(N) time with O(1) extra space, where N is the number of dictionaries
Examples
Example 1
Input: find_extreme_record([{'a': 10, 'b': 20}, {'a': 5, 'c': 15}, {'a': 10, 'd': 99}], 'a', 'MAX')
Output: {'a': 10, 'b': 20}
Example 2
Input: find_extreme_record([{'id': 1, 'score': -5}, {'id': 2}, {'id': 3, 'score': -20}, {'id': 4, 'score': 0}], 'score', 'MIN')
Output: {'id': 3, 'score': -20}
Example 3
Input: find_extreme_record([{'x': 1}, {'y': 2}], 'z', 'MAX')
Output: None
Hints
Hint 1
Start by normalizing the mode parameter to uppercase and validating it before processing any records.
Hint 2
Track the best dictionary found so far along with its field value. Initialize both to None and update them only when you find a strictly better value.
Hint 3
Use strict inequality (< or >) rather than <= or >= to ensure that ties are broken in favor of the first occurrence.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution performs a single pass through the list of dictionaries, maintaining two pieces of state: the best dictionary found so far and its corresponding field value.
First, normalize and validate the mode parameter by converting it to uppercase and checking that it's either "MIN" or "MAX". This validation happens before processing any data to fail fast on invalid input.
Then iterate through each dictionary:
- Skip any dictionary that doesn't contain the target field
- If this is the first valid dictionary encountered, record it as the current best
- For subsequent dictionaries, compare their field value against the current best using strict inequality
- For
"MIN"mode: replace the best if the new value is strictly less than the current best - For
"MAX"mode: replace the best if the new value is strictly greater than the current best
- For
The strict inequality ensures that when multiple dictionaries have the same extreme value, only the first one is kept.
If no dictionary contains the specified field, both tracking variables remain None, which is the correct return value.
Why This Works
The algorithm maintains an invariant: after processing k valid dictionaries, best_value holds the minimum (or maximum) of all their field values, and best_record points to the first dictionary that achieved this value.
The key insight for tie-breaking is using strict comparison operators. When a later dictionary has the same value as the current best, the condition value < best_value (or value > best_value) evaluates to false, so no replacement occurs. This preserves the first occurrence.
Checking field not in record before accessing record[field] prevents KeyError exceptions on sparse dictionaries, and checking best_record is None handles initialization cleanly without sentinel values.
Complexity
Time: O(N) where N is the number of dictionaries. Each dictionary is visited once, and checking membership in a dictionary is O(1) average case.
Space: O(1) auxiliary space. Only two tracking variables are maintained. The function returns a reference to an existing dictionary rather than creating a copy.
Solution Code
def find_extreme_record(records, field, mode="MAX"):
normalized = mode.upper()
if normalized not in ("MIN", "MAX"):
raise ValueError("mode must be MIN or MAX")
best_record = None
best_value = None
for record in records:
if field not in record:
continue
value = record[field]
if best_record is None or (normalized == "MIN" and value < best_value) or (normalized == "MAX" and value > best_value):
best_record = record
best_value = value
return best_record