You are given a string s
of lowercase English letters and an integer array shifts
of the same length.
Call the shift of a letter, the next letter in the alphabet, (wrapping around so that ‘z’ becomes ‘a’).
'a'
by 1 gives 'b'
, and shifting 'z'
by 1 gives 'a'
.Now for each shifts[i] = x
, we want to shift the first i + 1
letters of s
, x
times.
Return the final string after all such shifts to s
are applied.
Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation:
We start with "abc".
After shifting the first 1 letters by 3, we have "dbc".
After shifting the first 2 letters by 5, we have "igc".
After shifting the first 3 letters by 9, we have "rpl".
1 <= s.length <= 10^5
s
consists of lowercase English letters.shifts.length == s.length
0 <= shifts[i] <= 10^9
shifts
array in reverse.def shiftingLetters(s: str, shifts: List[int]) -> str:
n = len(s)
# Initialize cumulative shifts
cumulative_shift = 0
# Initialize result list of characters
result = list(s)
# Traverse shifts in reverse to accumulate the shifts
for i in range(n - 1, -1, -1):
cumulative_shift += shifts[i]
cumulative_shift %= 26
# Shift the i-th character
new_char = chr((ord(s[i]) - ord('a') + cumulative_shift) % 26 + ord('a'))
result[i] = new_char
# Join the list into the final string
return ''.join(result)
O(n)
to construct the result string.This solution should handle the given constraints efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?