Who Came First

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
mid
Asked in
CVS Health

Problem

Given items, an upstream feed of member IDs in the exact order they were scanned during a shift, return each member once, in the position it was first seen. The same member often gets scanned several times.

The feed repeats itself. Keep each member only the first time it speaks.

Example 1

Input:

items = [101,102,101,103,102]

Output:

[101,102,103]

Example 2

Input:

items = ["C9","C9","A7","B2","A7"]

Output:

["C9","A7","B2"]

Worked solution and explanation

Why this problem exists in real interviews

This is order-preserving deduplication wearing a member-feed costume. Everyone knows set(items) strips duplicates. The trap is that a set also throws away order, so list(set(items)) hands back the IDs in whatever order the hash table happens to hold them. The whole challenge is two requirements at once: one copy per member, and each copy sitting where that member was first scanned. The obvious one-liner is subtly wrong, and the clean fix shows whether you actually know your standard library.


Break down the requirements

Step 1: Track what you have already emitted

You need O(1) membership tests as you walk the feed, so a set of seen IDs is the right companion structure. A list-based if x not in result check is correct but makes the whole thing O(n^2), which an interviewer will notice on a million-row feed.

Step 2: Emit on first sight only

Iterate the feed in its given order. The first time an ID shows up, append it to the output and mark it seen; every later repeat is skipped. Because you append in scan order, the first-seen position comes for free: 'C9' leads the result even though 'A7' sorts ahead of it.

Step 3: Let an empty feed answer itself

No special case is needed: an empty input produces an empty output through the same pass. Adding a guard clause here is noise, not care.


The solution

`dict.fromkeys` preserves insertion order and dedupes in one pass
def unique_in_order(items):
    return list(dict.fromkeys(items))

Since Python 3.7 a dict preserves insertion order, so dict.fromkeys(items) creates one key per distinct value in first-seen order, and repeats collapse into the key that already exists. Wrapping it in list() returns exactly the ordered, deduplicated sequence as a fresh list, leaving the feed untouched. It is one pass, O(n), and it reads like the requirement.

Wrong: `list(set(items))`
Dedupes correctly, but a set has no order, so the IDs come back in hash order. On the member feed that scrambles the scan sequence the downstream audit depends on.
Right: `list(dict.fromkeys(items))`
Dedupes AND keeps first-seen order at the same O(n) cost, with no extra structure to manage. An explicit seen-set loop is equivalent and just as acceptable if you prefer it spelled out.

Common follow-up questions