We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Replace All Digits with Characters

Number: 1954

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a 0-indexed string where characters occupy the even indices and digits occupy the odd indices, replace each digit by shifting the previous character forward by the digit's value (using the defined shift operation). The shifted character will always be a lowercase English letter not exceeding 'z'. Return the modified string.


Key Insights

  • The string follows a specific format: letters at even indices and digits at odd indices.
  • Only the odd-indexed digits need processing; they indicate how much to shift the preceding character.
  • Shifting is achieved by converting the character to its ASCII value, adding the numeric value, and converting back to a character.
  • The operation is straightforward with a linear pass over the string.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string, as we iterate over the string once. Space Complexity: O(n) for the result string storage, although modifications can be done in-place if allowed.


Solution

We iterate through the string and for every digit at an odd index, we use the preceding letter to compute its shifted character. The shift operation converts the letter to its ASCII code, adds the integer value of the digit, and then converts it back to a character. This results in a new string with all digits replaced by their computed shifted characters.


Code Solutions

# Python solution
def replaceDigits(s: str) -> str:
    # Convert the string into a list for easy modification.
    s_list = list(s)
    # Iterate over each odd index (since 0-indexed, these are digit positions)
    for i in range(1, len(s_list), 2):
        # Get the previous character and digit (converted to int)
        prev_char = s_list[i - 1]
        shift_amount = int(s_list[i])
        # Calculate new character using ASCII operations
        new_char = chr(ord(prev_char) + shift_amount)
        s_list[i] = new_char  # Replace digit with new character
    # Join the list back into a string and return
    return ''.join(s_list)

# Example usage:
# print(replaceDigits("a1c1e1"))  # Output: "abcdef"
← Back to All Questions