Replace All Digits with Characters - Problem

You're given a string with a special pattern: letters are at even indices and digits are at odd indices. Your task is to transform this string by replacing each digit with a shifted character.

The shift operation works like this: shift(c, x) takes a character c and shifts it x positions forward in the alphabet. For example:

  • shift('a', 5) = 'f' (a → b → c → d → e → f)
  • shift('x', 0) = 'x' (no shift)
  • shift('m', 3) = 'p' (m → n → o → p)

For each digit at an odd index i, replace it with shift(s[i-1], s[i]) - shift the previous character by the digit amount.

Goal: Return the transformed string with all digits replaced by their corresponding shifted characters.

Input & Output

example_1.py — Basic Pattern
$ Input: s = "a1c1e1"
Output: "abcdef"
💡 Note: At index 1: shift('a', 1) = 'b'. At index 3: shift('c', 1) = 'd'. At index 5: shift('e', 1) = 'f'. Result: 'a' + 'b' + 'c' + 'd' + 'e' + 'f' = "abcdef"
example_2.py — Different Shifts
$ Input: s = "a1b2c3d4e"
Output: "abbdcgdie"
💡 Note: Processing each position: a(keep) → shift('a',1)='b' → b(keep) → shift('b',2)='d' → c(keep) → shift('c',3)='f' → d(keep) → shift('d',4)='h' → e(keep). Wait, let me recalculate: 'a' + shift('a',1)='b' + 'b' + shift('b',2)='d' + 'c' + shift('c',3)='f' + 'd' + shift('d',4)='h' + 'e' = "abbdcfdie"
example_3.py — Zero Shifts
$ Input: s = "a0c0"
Output: "acac"
💡 Note: At index 1: shift('a', 0) = 'a' (no change). At index 3: shift('c', 0) = 'c' (no change). Result: 'a' + 'a' + 'c' + 'c' = "acac"

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists only of lowercase English letters and digits 0-9
  • s[i] is a lowercase English letter if i is even
  • s[i] is a digit if i is odd
  • shift(s[i-1], s[i]) will never exceed 'z'

Visualization

Tap to expand
String Pattern: Letters (Even) → Digits (Odd) → Letters (Even) ...aindex 01index 1cindex 21index 3eindex 41index 5shift(a,1)=bshift(c,1)=dshift(e,1)=fabcdefFinal Result: "abcdef"
Understanding the Visualization
1
Identify Pattern
Letters at even indices (0,2,4...), digits at odd indices (1,3,5...)
2
Apply Shifts
For each digit, shift the previous letter forward in the alphabet
3
Build Result
Combine original letters with shifted characters to form the final string
Key Takeaway
🎯 Key Insight: This is a simple one-pass string transformation where we only need to look at the previous character to calculate each shift, making it very efficient with O(n) time complexity.
Asked in
LeetCode 25 Google 15 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen