Sponsored
Sponsored
In this approach, we calculate the cumulative shift for each character and apply it directly. We start from the first character and compute the required shift by summing all applicable shift values for each character position. After calculating the cumulative shift, we adjust each character in the string accordingly.
Time Complexity: O(n^2)
where n
is the length of the string due to the nested loops.
Space Complexity: O(1)
since no extra space other than for variables is used.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5string shiftingLetters(string s, vector<int>& shifts) {
6 for (int i = 0; i < s.length(); i++) {
7 int totalShift = 0;
8 for (int j = 0; j <= i; j++) {
9 totalShift += shifts[j];
10 }
11 totalShift %= 26;
12 s[i] = (s[i] - 'a' + totalShift) % 26 + 'a';
13 }
14 return s;
15}
16
17int main() {
18 string s = "abc";
19 vector<int> shifts = {3, 5, 9};
20 cout << shiftingLetters(s, shifts) << endl;
21 return 0;
22}
This C++ approach is similar to the C approach by iterating over shift values to compute cumulative shifts. It then modifies each character with ASCII calculations.
This approach optimizes the shift of letters by computing the cumulative shift from the last character to the first. It reduces the overhead of multiple summations using a single pass through the shifts array from back to front.
Time Complexity: O(n)
, processing each character once.
Space Complexity: O(1)
.
1public
This Java solution optimizes by updating shifts cumulatively from the end, improving efficiency and clarity.