algoadvance

Leetcode 1844. Replace All Digits with Characters

Problem Statement:

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

There is a function shift(c, x), where c is a character and x is a digit, that shifts c forward in the alphabet x times. For example, shift('a', 1) = ‘b’ and shift('x', 2) = ‘z’.

Return the final string after applying shift to all the digits in s.

Clarifying Questions:

  1. Input Constraints:
    • The length of s is even and ranges from 1 to 1000.
    • s contains only lowercase English letters and digits.
    • The digits are between 0 and 9.
  2. Output:
    • A string with all digits replaced with the corresponding shifted characters.

Strategy:

  1. Iterate Through the String:
    • Traverse the string character by character using a loop.
    • For characters at even indices (0, 2, 4, …), they are kept as-is because they are letters.
    • For characters at odd indices (1, 3, 5, …), convert the digit to an integer and shift the preceding letter by that integer value.
  2. Shifting Mechanism:
    • Use the ASCII value of the letter to shift it forward by the number given as the digit.
    • Convert the result back to a character and append it to the resulting string.
  3. Result Construction:
    • Build the final resulting string by appending each new character after transformation.

Time Complexity:

Code:

#include <iostream>
#include <string>
using namespace std;

string replaceDigits(string s) {
    for (int i = 1; i < s.size(); i += 2) {
        int digit = s[i] - '0';   // Convert character at odd index to corresponding digit
        s[i] = s[i - 1] + digit;  // Shift the preceding character
    }
    return s;
}

// Main function to test the implementation
int main() {
    string input = "a1b2c3d4e"; 
    cout << "Original String: " << input << endl;
    string result = replaceDigits(input);
    cout << "Transformed String: " << result << endl;
    return 0;
}

The replaceDigits function iterates through the string, checking for digits at odd indices, converts each to an integer, shifts the preceding character accordingly, and updates the string in place. The main function demonstrates how to use this utility with an example.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI