The First Encounter
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
- Nintendo
Problem
Given a string, return a dict mapping each distinct character to the index of its first occurrence.
Every character has a story - but only if you remember where it started.
Example 1
Input:
s = "hello"
Output:
{"h":0,"e":1,"l":2,"o":4}Example 2
Input:
s = "abc"
Output:
{"a":0,"b":1,"c":2}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
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 resultCommon 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.)