Shifting Letters

medium string prefix-sum

Problem

Given a string s and an integer array shifts of the same length, shift the first i+1 letters of s by shifts[i] (lowercase, wrapping). Return the resulting string.

Inputs = "abc", shifts = [3,5,9]
Output"rpl"
Cumulative shifts from the right are 17, 14, 9.

def shiftingLetters(s, shifts):
    n = len(s)
    total = 0
    res = list(s)
    for i in range(n - 1, -1, -1):
        total = (total + shifts[i]) % 26
        res[i] = chr((ord(s[i]) - ord('a') + total) % 26 + ord('a'))
    return "".join(res)
function shiftingLetters(s, shifts) {
  const n = s.length;
  let total = 0;
  const res = s.split("");
  for (let i = n - 1; i >= 0; i--) {
    total = (total + shifts[i]) % 26;
    res[i] = String.fromCharCode((s.charCodeAt(i) - 97 + total) % 26 + 97);
  }
  return res.join("");
}
class Solution {
  public String shiftingLetters(String s, int[] shifts) {
    int n = s.length();
    long total = 0;
    char[] res = s.toCharArray();
    for (int i = n - 1; i >= 0; i--) {
      total = (total + shifts[i]) % 26;
      res[i] = (char) ((res[i] - 'a' + total) % 26 + 'a');
    }
    return new String(res);
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    string shiftingLetters(string s, vector<int>& shifts) {
        long long total = 0;
        for (int i = s.size() - 1; i >= 0; i--) {
            total = (total + shifts[i]) % 26;
            s[i] = (s[i] - 'a' + total) % 26 + 'a';
        }
        return s;
    }
};
Time: O(n) Space: O(n)