The Last Instance

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
Citadel

Problem

An on-call engineer noticed the tag feed in items is full of stale repeats, because a reader re-reports a tag every time it cycles back into range. Collapse it so each value survives exactly once, sitting where it was last reported.

When duplicates appear, only the last one counts.

Example 1

Input:

items = [1,2,1,3,2]

Output:

[1,3,2]

Example 2

Input:

items = [3,3,3]

Output:

[3]

Worked solution and explanation

Why this problem exists in real interviews

This tests order-preserving deduplication keeping the last occurrence, a pattern used in configuration override systems. It probes reverse iteration and set-based seen tracking.


Break down the requirements

Step 1: Iterate in reverse

Process from right to left so the first encounter of each value is its last forward occurrence.

Step 2: Track seen values

Use a set to skip duplicates.

Step 3: Reverse the result

Restore the original order.


The solution

Reverse scan with seen set
def keep_last(items: list) -> list:
    seen = set()
    result = []
    for i in range(len(items) - 1, -1, -1):
        if items[i] not in seen:
            seen.add(items[i])
            result.append(items[i])
    result.reverse()
    return result

Common follow-up questions