Replace All Digits with Characters - Problem

You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.

You must perform an operation shift(c, x), where c is a character and x is a digit, that returns the xth character after c.

  • For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.

For every odd index i, you want to replace the digit s[i] with the result of the shift(s[i-1], s[i]) operation.

Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.

Note that shift(c, x) is not a preloaded function, but an operation to be implemented as part of the solution.

Input & Output

Example 1 — Basic Case
$ Input: s = "a1c1e1"
Output: "abcdef"
💡 Note: Digits at indices 1, 3, 5: '1' shifts 'a'→'b', '1' shifts 'c'→'d', '1' shifts 'e'→'f'. Result: a + b + c + d + e + f = "abcdef"
Example 2 — Different Shifts
$ Input: s = "a1b2c3"
Output: "abbdcf"
💡 Note: Index 1: 'a' + 1 = 'b', Index 3: 'b' + 2 = 'd', Index 5: 'c' + 3 = 'f'. Result: a + b + b + d + c + f = "abbdcf"
Example 3 — Zero Shift
$ Input: s = "a0c0e0"
Output: "acacee"
💡 Note: Zero shift means same character: 'a' + 0 = 'a', 'c' + 0 = 'c', 'e' + 0 = 'e'

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters and digits
  • 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]) ≤ 'z' for all odd indices i

Visualization

Tap to expand
Replace All Digits with Characters INPUT String s = "a1c1e1" 0 1 2 3 4 5 a 1 c 1 e 1 Even index (letter) Odd index (digit) shift(c, x) operation: shift('a', 1) = 'b' shift('c', 1) = 'd' shift('e', 1) = 'f' Returns xth char after c ALGORITHM STEPS 1 Initialize Result Create empty string builder 2 Loop Through String For each index i in s 3 Check Index Parity If even: append s[i] If odd: apply shift 4 Apply Shift Operation s[i-1] + digit value Append new character i=1: a+1=b i=3: c+1=d i=5: e+1=f char + int(digit) --> new char FINAL RESULT Output: "abcdef" 0 1 2 3 4 5 a b c d e f Transformations Applied: 'a' --> 'a' (kept) '1' --> 'b' (a+1) 'c' --> 'c' (kept) '1' --> 'd' (c+1) 'e' --> 'e' (kept) '1' --> 'f' (e+1) OK - All digits replaced! Time: O(n) | Space: O(n) Key Insight: The pattern alternates between letters (even indices) and digits (odd indices). Each digit tells us how many positions to shift from the previous character. By iterating once and using character arithmetic (char + digit), we can build the result in-place with O(n) time complexity. TutorialsPoint - Replace All Digits with Characters | In-Place String Building Approach
Asked in
Amazon 15 Facebook 12
34.0K 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