# The First Encounter

> Every character has a story - but only if you remember where it started.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a string, return a dict mapping each distinct character to the index of its first occurrence.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **first-occurrence tracking with a dict**, a pattern used in deduplication and data quality tools. It probes whether a candidate correctly skips updates for already-seen keys.

---

### Break down the requirements

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

Process each character with its position.

#### Step 2: Record only the first occurrence

If the character is not yet in the dict, add it with the current index. If it is already present, skip it.

---

### The solution

**First-occurrence index mapping**

```python
def first_occurrence(s: str) -> dict:
    result = {}
    for i in range(len(s)):
        ch = s[i]
        if ch not in result:
            result[ch] = 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**
>
> The `if ch not in result` guard. Without it, later occurrences overwrite earlier ones, producing last-occurrence instead of first.

> **Common Pitfall**
>
> Using `dict.setdefault(ch, i)` without understanding it only sets when absent. This actually works correctly here but candidates should be able to explain why.

---

## Common follow-up questions

- How would you return the last occurrence instead? _(Tests removing the guard so every occurrence overwrites the previous.)_
- What if you needed both first and last occurrence? _(Tests maintaining two dicts or a dict of tuples.)_
- How would you handle this for a streaming input? _(Tests that first-occurrence tracking works naturally in streaming since you only need to check if seen before.)_

## Related

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