First Occurrence Map

Python data engineering interview problem. Difficulty: beginner. Pattern: Dictionaries. About 10 minutes. Free to practice.

Map each distinct character to the index of its first occurrence. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Sometimes you need to know where each character first shows up in a word, for example when you search for the first occurrence of a letter. Write a function first_occurrence_map(s) that takes a string and returns a dictionary. Each key is a different character from the string, and each value is the index (position) where that character appears for the first time. Positions start at 0. For 'hello' the answer is {'h': 0, 'e': 1, 'l': 2, 'o': 4}. The letter l appears at positions 2 and 3, but only the first one, 2, is stored. Keep the print lines in the editor. They call your function when you click Run.

Requirements

  • Return a dictionary with one key for each distinct character in s.
  • Each value is the index of the first time that character appears.
  • Keys appear in the order the characters were first seen.
  • Never replace a stored index with a later one.

Constraints

  • s is a non-empty string.
  • Indexes start at 0, so the first character has index 0.
  • Spaces and punctuation count as characters too.

Examples

Input: first_occurrence_map('hello') Output: {'h': 0, 'e': 1, 'l': 2, 'o': 4} Second 'l' is ignored.

Topics: lakebench, python, hash map, strings.

More Python interview questions · All interview problems · Learn data engineering

beginner

First Occurrence Map

Interview-style drill: Map each distinct character to the index of its first occurrence.

Implement `first_occurrence_map(s: str) -> dict` mapping each distinct character to the index of its first occurrence. Example: `"hello"` → `{'h': 0, 'e': 1, 'l': 2, 'o': 4}`. Keep the harness.