Problem statement

https://leetcode.com/problems/shifting-letters/

Solution

Let us condised example s = "abc", shifts = [3,5,9] for better understanding. We need to shift first letter by 3 positions, the next letter by 3 + 5 positions and the last one by 3 + 5 + 9 positions. So, we can notice, that in fact we have here cumulative sums, but they star from the end. In python we can easily find them, using accumulate function, and we need to apply it to reversed shifts and then reverse it again in the end.

Finally, what we need to do is just apply calculated shifts to each letter in string, also taking into account that when we reach z we go to a.

Complexity

TIme complexity is O(n), space is O(n) as well.

Code

class Solution:
    def shiftingLetters(self, S, shifts):
        SH = list(accumulate(shifts[::-1]))[::-1]
        return "".join(chr((ord(s) - 97 + SH[i]) % 26 + 97) for i, s in enumerate(S))