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

An upstream feed hands you member IDs in the exact order they were scanned during a shift, and the same member often gets scanned several times. Collapse the feed so each member appears once, in the position it was first seen.

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

Example 1

Input:

items = []

Output:

[]

Example 2

Input:

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

Output:

[101,102,103]

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 an arbitrary hash ordering. The whole challenge is the tension between two requirements at once: keep one copy per member AND keep each at its first-seen position. Interviewers ask it because the obvious one-liner is subtly wrong, and the clean fix tells them 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 turns 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, record it in the output and mark it seen; every later repeat is skipped. Because you append in iteration order, first-seen position falls out for free.

Step 3: Let an empty feed answer itself

No special case needed: an empty input produces an empty output through the same loop. Resist adding a guard clause; it is negative signal here.


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 dict preserves insertion order, so dict.fromkeys(items) builds a key per distinct value in first-seen order, collapsing repeats automatically. Wrapping it in list() returns exactly the ordered, deduplicated sequence. It is the idiom a senior reaches for because it is one pass, O(n), and reads like the spec.

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

Common follow-up questions