🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
You have a log where every update to a record is appended as a new line. When the
same id appears more than once, the later line has overwritten the earlier one.
Implement deduplicate(records), which collapses this list down to one line per
id.
records = [
{"id": 1, "value": 10},
{"id": 2, "value": 20},
{"id": 1, "value": 30},
]
id key.id are free-form and may differ between records.id may be an integer or a string.Return the cleaned-up list of records.
deduplicate(records)
# [{"id": 1, "value": 30}, {"id": 2, "value": 20}]
Two things must hold at the same time.
id repeats, only the last record for it survives.id first appeared.In the example id=1 appears twice. The value that survives is the later one, 30.
Its position, however, is the front, because that is where id=1 first appeared.
So id=1 comes before id=2 in the result.
Satisfying just one of them is easy.
Walking backwards and keeping each id the first time you see it gives the right
values but reverses the order. Walking forwards and keeping each id the first
time you see it gives the right order but stale values.
A property of Python dictionaries gets you both at once. Store records keyed by
id: assigning to a key that already exists replaces the value, but leaves that
key sitting where it was first inserted.
id appears three or more times, only the last one survives.Implement deduplicate(records).