Algorithmscharacter index mapping

Character Index Mapping (Position ↔ Symbol)

TT
Testlaa Team
May 14, 20261 min read

Index mapping ties each character to its position: enumerate(s) pairs (i, ch), while inverse maps like last_index[ch] answer “where did this symbol last appear?”

Why this shows up in the real world

Spell-check underlines map wrong characters back to editor column indices. DNA alignments map nucleotide symbols to reference coordinates.

Core idea (explained for students)

Forward pass: for i, ch in enumerate(s): .... Reverse lookups: dict from character to list of indices, or latest index only depending on the problem.

Try this in Python

def first_indices(s: str) -> dict[str, int]:
    out = {}
    for i, ch in enumerate(s):
        out.setdefault(ch, i)
    return out


print(first_indices("abac"))

Common mistakes

  • Off-by-one when converting “1-based column” UI specs to Python indices.
  • Storing huge lists per character without pruning when only last index matters.

Key takeaways

  • Choose last vs first occurrence deliberately in sliding window problems.
  • enumerate is your default tool—memorize the idiom.

Tags:

StringsPythonStudents