# The Last Seen Map

> For each character, where did it appear last?

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a string, return a dict mapping each distinct character to its last index (rightmost occurrence) in the string.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the simplest dict accumulation pattern: **overwriting on each encounter**. Unlike first-occurrence, this pattern lets later occurrences naturally replace earlier ones.

---

### Break down the requirements

#### Step 1: Iterate through the string with index

Process each character and its position.

#### Step 2: Overwrite the dict entry on every occurrence

The last write for each character will be its final (last) index.

---

### The solution

**Overwrite-on-encounter index mapping**

```python
def last_seen(s: str) -> dict:
    result = {}
    for i in range(len(s)):
        result[s[i]] = i
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the string length.
> 
> **Space:** O(k) where k is the number of unique characters.

> **Interviewers Watch For**
>
> Whether you realize this is simpler than first-occurrence. No guard needed; just overwrite.

> **Common Pitfall**
>
> Adding a guard like `if s[i] not in result`. This would turn it into a first-occurrence map.

---

## Common follow-up questions

- How would you track both first and last occurrence? _(Tests using a dict of `{'first': i, 'last': i}` or a tuple.)_
- What if you needed this for a streaming input? _(Tests that the overwrite pattern works naturally in streaming.)_
- How would you find the character with the largest gap between first and last occurrence? _(Tests combining first and last occurrence maps and computing differences.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_last_seen_map)
- [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.