Replace All Digits with Characters
Problem
You are given a string s of even-indexed lowercase letters and odd-indexed digits. For every odd index i, replace the digit s[i] with the letter you get by shifting the previous character s[i-1] forward by s[i] positions in the alphabet. Even-indexed letters stay as they are. Return the resulting string.
s = "a1c1e1""abcdef"def replace_digits(s):
res = list(s)
for i in range(1, len(s), 2):
prev = res[i - 1]
shift = int(s[i])
res[i] = chr(ord(prev) + shift)
return "".join(res)
function replaceDigits(s) {
const res = s.split("");
for (let i = 1; i < s.length; i += 2) {
const prev = res[i - 1].charCodeAt(0);
const shift = s.charCodeAt(i) - 48;
res[i] = String.fromCharCode(prev + shift);
}
return res.join("");
}
class Solution {
public String replaceDigits(String s) {
char[] res = s.toCharArray();
for (int i = 1; i < res.length; i += 2) {
int shift = res[i] - '0';
res[i] = (char) (res[i - 1] + shift);
}
return new String(res);
}
}
string replaceDigits(string s) {
for (int i = 1; i < (int)s.size(); i += 2) {
int shift = s[i] - '0';
s[i] = s[i - 1] + shift;
}
return s;
}
Explanation
The string follows a strict pattern: even positions hold letters, odd positions hold digits. Every digit is just an instruction — take the letter just before me and walk that many steps up the alphabet.
So we copy the string into a mutable array and walk only the odd indices 1, 3, 5, …. At each one we read the previous character res[i-1] (which is always a letter that has already been finalized) and the digit value s[i].
The shift is pure character arithmetic: chr(ord(prev) + digit) in Python, prev + shift on the underlying char code in Java/C++. We overwrite the digit slot with that new letter and move on.
Because even positions are never touched and each odd position depends only on the fixed letter to its left, a single left-to-right pass is enough — no recomputation, no second pass.
Example: "a1c1e1". Index 1: shift 'a' by 1 → 'b'. Index 3: shift 'c' by 1 → 'd'. Index 5: shift 'e' by 1 → 'f'. Result "abcdef".