How would you use a Python dictionary keyed by customer_id to keep only the latest record per customer, overwriting a record only when the new updated_at timestamp is higher?
💡 Model Answer
You can iterate over the list of records once, maintaining a dictionary that maps each customer_id to the record with the most recent updated_at. For each incoming record, check if its customer_id is already in the dictionary. If it isn’t, simply add the record. If it is, compare the updated_at of the existing record with the new one; if the new updated_at is greater, replace the entry. This guarantees that after the pass, the dictionary contains only the latest record for each customer. The algorithm runs in O(n) time, where n is the number of records, and uses O(k) space, where k is the number of unique customers. Example code:
latest = {}
for rec in records:
cid = rec['customer_id']
if cid not in latest or rec['updated_at'] > latest[cid]['updated_at']:
latest[cid] = rec# latest now holds the newest record per customer.
This approach is efficient for both batch and streaming scenarios and can be extended to handle more complex merging logic if needed.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500