progress

~/problems / Arrays & hashing / Sorting, custom keys, coordinate compression

Minimum record by key

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium assessment 3 levels ~30 min Stripe

Level 1 The smallest value of one field

A tiny database holds records. A record is a dict from a field name (a string) to an integer value. Records don't all have the same fields: one may have "age" and "score", the next only "score".

Write min_by_key(records, key) -> dict: return the record with the smallest value for the field key.

  • A record that doesn't have key counts as having the value 0 for it.
  • If several records share the smallest value, return the one that comes first in records.
  • Return the record itself (or an equal dict). Don't change records or any record in it.

records always holds at least one record.

records = [{"a": 3, "b": 1}, {"a": -2}, {"b": 5}]
min_by_key(records, "a")   # {"a": -2}
min_by_key(records, "b")   # {"a": -2}: it has no "b", so it counts as 0, which beats 1 and 5
min_by_key(records, "c")   # {"a": 3, "b": 1}: every record counts as 0, so the first one wins

Constraints: up to 10^5 records with up to 10 fields each. Values are between -10^9 and 10^9. Field names are 1 to 10 lowercase letters.

Later levels add more ways to compare records, so keep the comparison in one place.

⭐ Bonus: a speed test with 30,000 records earns a star. One pass over the records is enough; you don't need to sort.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Sorting, custom keys, coordinate compression. sorted(key=...), multi-key and stable sorts, cmp_to_key, compressing coordinates.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc