Similar Problems

Similar Problems not available

Shifting Letters Ii - Leetcode Solution

Companies:

LeetCode:  Shifting Letters Ii Leetcode Solution

Difficulty: Medium

Topics: string prefix-sum array  

The Shifting Letters II problem on Leetcode requires us to shift after each query, the first k letters of a given string by an integer value. Here's a detailed solution for this problem:

  1. First, we need to create a function to shift the letters of a string by a given integer value. We can do this by looping through the string and converting each character to its ASCII value. We can then add the shift value and use the modulus operator to handle cases where the ASCII value goes beyond the range of lowercase or uppercase letters. Finally, we convert the ASCII value back to a character and append it to our result string.
def shift_string(s: str, shifts: int) -> str:
    result = ""
    for i in range(len(s)):
        ascii_val = ord(s[i])
        shift = shifts % 26
        if ascii_val >= 97 and ascii_val <= 122:
            ascii_val = (ascii_val - 97 + shift) % 26 + 97
        elif ascii_val >= 65 and ascii_val <= 90:
            ascii_val = (ascii_val - 65 + shift) % 26 + 65
        result += chr(ascii_val)
        shifts -= shift
    return result
  1. Once we have our shift_string function, we can use it to shift the first k letters of our given string for each query. We can loop through each query and call the shift_string function with the substring of our string from 0 to k. We then concatenate the shifted substring with the unshifted portion of our string. We repeat this process for each query.
def shiftingLetters(s: str, shifts: List[int]) -> str:
    result = s
    for i in range(len(shifts)-1, -1, -1):
        result = shift_string(result[:i+1], shifts[i]) + result[i+1:]
    return result
  1. In our main function, we first check if our given string and shifts list are not empty. We then call the shiftingLetters function with our given string and shifts list as parameters and return the resulting shifted string.
def main():
    s = "abc"
    shifts = [3,5,9]
    if s and shifts:
        shifted_string = shiftingLetters(s, shifts)
        print(shifted_string) # "rpl"

Overall, the solution involves creating a function to shift the letters of a string by a given integer value, and then looping through each query to shift the first k letters of our given string. We then concatenate the shifted substring with the unshifted portion of our string and repeat the process for each query.

Shifting Letters Ii Solution Code

1