The First of Their Kind
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Amazon
Problem
An ingestion feed hands you records in arrival order, and the same key value can reappear whenever an upstream producer retries a record it already sent. The feed can run to millions of records, so in a single pass keep only the first record for each distinct value of key, never rescanning the ones you have already kept.
When the same record arrives twice, only the first one survives.
Example 1
Input:
records = [{"user":"mona","event_id":"a1"},{"user":"raj","event_id":"a2"},{"user":"mona-retry","event_id":"a1"},{"user":"ivy","event_id":"a3"}], key = "event_id"Output:
[{"user":"mona","event_id":"a1"},{"user":"raj","event_id":"a2"},{"user":"ivy","event_id":"a3"}]Example 2
Input:
records = [{"user":"lia","event_id":"b1"},{"user":"no-id-1"},{"user":"lia-dup","event_id":"b1"},{"user":"no-id-2"}], key = "event_id"Output:
[{"user":"lia","event_id":"b1"},{"user":"no-id-1"},{"user":"no-id-2"}]Worked solution and explanation
Retries in an arrival-ordered feed
A producer that retries is giving you at-least-once delivery, and the consumer's job is to make the repeat harmless. The pattern is an order-preserving dedup: walk the feed once, remember every key value you have already kept, and let a record through only the first time its value shows up. A question that asks for the first record per value, in arrival order, in one pass is asking for it. The whole answer hangs on the structure that tells you whether a value has been seen without looking back through the output.
Step 1: Keep a set of values beside the output
The output list holds whole records in order; seen holds only the key values behind them. A membership test on a set is a hash lookup, so its cost stays flat whether you have kept 10 records or 10 million.
Step 2: Test and add in the same branch
value not in seen decides whether the record is new. When it is, seen.add(value) and result.append(record) happen together, so the first arrival wins and every later record with that value falls through. In example 1, 'mona-retry' arrives with 'a1' already in seen and is dropped.
Step 3: Handle the record with no key first
Example 2 has 2 records with no event_id at all, and both come back. A record without the field has nothing to compare, so it cannot be a retry of anything you can identify. The key not in record check appends it and moves on with continue before any value is read.
def deduplicate(records, key):
seen = set()
result = []
for record in records:
if key not in record:
# No key to dedup on; keep it in order.
result.append(record)
continue
value = record[key]
if value not in seen:
seen.add(value)
result.append(record)
return result- Scan what you kept
- Tracking kept values in a list and testing
value not in kept_valuesreturns the same output, but each test walks the list. With 1 million distinct values that is about 500 billion comparisons, which is the rescanning the statement rules out. - Ask a `set`
value not in seenon a set hashes the value and checks one bucket. The millionth record costs the same as the first, so the pass stays linear.
Where 'no-id-2' goes missing
The tempting shortcut is record.get(key), which removes the membership check and the continue. It also turns every keyless record into the same value, None, and None is hashable, so it goes into seen like any other value.
def deduplicate(records, key):
seen = set()
result = []
for record in records:
value = record.get(key) # a missing key becomes None
if value not in seen:
seen.add(value)
result.append(record)
return resultOn example 2 this returns 2 records, the 'lia' and 'no-id-1' ones: 'no-id-2' is dropped as a duplicate of None.
Common follow-up questions
- What happens when the distinct
keyvalues no longer fit in memory?Partition the feed by a hash of the value so each partition's set fits, or keep the seen ids in an external store with a retention window. Retries usually arrive close to the original, so a bounded window catches most of them at a fixed memory cost.
- How would you stream records out instead of returning a list?
Turn the function into a generator that yields each kept record where it now appends, with
seenas the only state. That takes the output list out of memory, which matters when the consumer writes records as they arrive. - What if the value under
keyis a list or a dict?seen.add(value)raisesTypeErrorbecause the value is unhashable, so you either convert it to a hashable form such as a tuple or set the record aside as malformed. Feeds built from JSON carry nested ids more often than their schemas admit. - The business now wants the latest record per
keyvalue, still in first-arrival order. What changes?Keep a dict from each value to its index in
resultand overwrite that slot when a repeat arrives. Some producers re-send an id to correct a record, so ask whether a repeat is a retry or a correction before choosing which one wins. - Which tests would you write first?
An empty feed, a feed with no repeats, a repeat separated by other records, 2 keyless records, and a present
keyholdingNone. The last 2 pin down the difference between a missing field and an empty value, which is where implementations disagree.