Character-to-index mapping is the transformation of a character to an integer index by subtracting the base character’s ASCII value. For lowercase English letters, index = ch - 'a' maps ‘a’→0, ‘b’→1, …, ‘z’→25. This enables using characters as array indices.
Computers store characters as integer codes (ASCII, UTF-8). When characters are contiguous in the encoding — as lowercase letters ‘a’–‘z’ are — subtracting the base character’s code produces a zero-based index. This is the bridge between the character domain and the array-index domain, and it is what makes frequency arrays possible.
- Determine the base character (e.g., ‘a’ for lowercase letters, ‘A’ for uppercase)
- Get the ASCII value of the target character:
int(ch) - Subtract the ASCII value of the base character:
int(ch) - int('a') - The result is a zero-based index suitable for array access
For 'a' through 'z', ASCII values are 97–122, so ch - 'a' yields 0–25.
Given ASCII encoding where :
- O(1) computation — simple integer subtraction
- Requires characters to be contiguous in the encoding
- Only works for a single case at a time (lowercase or uppercase, not both)
- Assumes ASCII encoding (works in C++ on all major platforms)
- The inverse operation is
i + 'a'
- Built from: Direct Array Access — relies on ASCII values being contiguous integers
- Builds into: Frequency Array — the mapping is required to index the frequency array
- Builds into: Index-to-Character Conversion — the mathematical inverse operation
- Contrasts with: ASCII Math Elimination — hash maps remove the need for this conversion entirely
- Related: Known Range Assumption — only works when character range is known and contiguous
- Applying
ch - 'a'to an uppercase character ‘A’–‘Z’ (ASCII 65–90) gives negative indices — undefined behavior - Applying it to digits, punctuation, or spaces gives unpredictable indices
- Mixing cases silently produces wrong results — ‘A’ maps to -32 (wraps around for unsigned, negative for signed)
- C++
charmay be signed or unsigned depending on platform —ch - 'a'with negativecharvalues is implementation-defined - The mapping assumes ASCII; EBCDIC systems do not have contiguous letters