Skip to content

39. Keep the Latest Record per Key

Difficulty: Medium · Topic: Data wrangling

A change feed delivers several versions of each record, not in order. Write latest(records, key='id', ts='updated_at'): keep, for each value of key, the record with the greatest ts.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

rows = [
    {'id': 2, 'status': 'new', 'updated_at': 1},
    {'id': 1, 'status': 'paid', 'updated_at': 5},
    {'id': 1, 'status': 'new', 'updated_at': 3},
    {'id': 2, 'status': 'paid', 'updated_at': 4},
]
latest(rows)

Expected: [{'id': 1, 'status': 'paid', 'updated_at': 5}, {'id': 2, 'status': 'paid', 'updated_at': 4}]

Hints

Hint 1One pass with a dict from key to the best record so far: O(n).
Hint 2Replace when the new timestamp is greater or equal: that keeps the later of two ties.
Hint 3record.get(ts) returns None for a missing field.

Learn the concepts

More Python problems

All Python problems