KatInterview

Find Dictionary with Extreme Field Value

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingdictionariesfilteringiteration

Last 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:

  1. Consider only dictionaries that actually contain the specified field.
  2. Return the dictionary whose value for field is the minimum or maximum, based on the mode parameter.
  3. When multiple dictionaries share the same extreme value, return the one that appears first in the list.
  4. Return None if the input list is empty or if no dictionary contains the specified field.
  5. Raise a ValueError if mode is 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^9 to 10^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.