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 <stdio.h>
2#include <string.h>
3
4void shiftLetters(char *s, int *shifts, int length) {
5 for (int i = 0; i < length; i++) {
6 int total_shift = 0;
7 for (int j = 0; j <= i; j++) {
8 total_shift += shifts[j];
9 }
10 total_shift %= 26;
11 s[i] = (s[i] - 'a' + total_shift) % 26 + 'a';
12 }
13}
14
15int main() {
16 char s[] = "abc";
17 int shifts[] = {3, 5, 9};
18 int length = sizeof(shifts) / sizeof(shifts[0]);
19 shiftLetters(s, shifts, length);
20 printf("%s\n", s);
21 return 0;
22}
This C implementation calculates the total shift for each character by iterating through the shift array and performs letter shifting using ASCII manipulations. Remember, we're cumulatively adjusting the character based on all previous shifts.
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.