The Last Seen Map

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

Problem

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

For each character, where did it appear last?

Example 1

Input:

s = "abracadabra"

Output:

{"a":10,"b":8,"r":9,"c":4,"d":6}

Example 2

Input:

s = "hello"

Output:

{"h":0,"e":1,"l":3,"o":4}

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
def last_seen(s: str) -> dict:
    result = {}
    for i in range(len(s)):
        result[s[i]] = i
    return result

Common follow-up questions