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.
1function shiftingLetters(s, shifts) {
2 let result = s.split('');
3 for (let i = 0; i < result.length; i++) {
4 let totalShift = 0;
5 for (let j = 0; j <= i; j++) {
6 totalShift += shifts[j];
7 }
8 totalShift %= 26;
9 result[i] = String.fromCharCode((result[i].charCodeAt(0) - 97 + totalShift) % 26 + 97);
10 }
11 return result.join('');
12}
13
14console.log(shiftingLetters('abc', [3, 5, 9]));
The JavaScript version leverages split and join for string manipulation, calculating cumulative shifts using nested loops.
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)
.
1#
This C code optimizes the shift calculations by continuously adding shifts from right to left, which avoids recalculating sums repeatedly.