# The Last Instance

> When duplicates appear, only the last one counts.

Canonical URL: <https://datadriven.io/problems/the_last_instance>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list, return a list containing only the last occurrence of each distinct value, preserving the order in which the last occurrences appear.

## 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.

> **Trick to Solving**
>
> Iterate the list in reverse, tracking seen elements in a set. Keep elements only on their first reverse encounter (which is the last occurrence in forward order). Then reverse the result to restore the original order.

---

### 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**

```python
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
```

> **Time and Space Complexity**
>
> **Time:** O(n) single pass plus O(n) reverse.
> 
> **Space:** O(n) for the seen set and result list.

> **Interviewers Watch For**
>
> Whether you correctly preserve order. The output should follow the last-occurrence positions, not the first-occurrence positions.

> **Common Pitfall**
>
> Keeping the first occurrence instead of the last. Without reverse iteration, the natural approach yields first-occurrence deduplication.

---

## Common follow-up questions

- How would you keep the first occurrence instead? _(Tests forward iteration with the same seen-set pattern.)_
- What if the list contains unhashable elements? _(Tests converting to tuples or using a different tracking method.)_
- How would you do this in a SQL context? _(Tests `ROW_NUMBER() OVER(PARTITION BY value ORDER BY position DESC)` with filter on `rn = 1`.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_last_instance)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.