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.
1using System;
2
3class Program {
4 static string ShiftingLetters(string s, int[] shifts) {
5 char[] result = s.ToCharArray();
6 for (int i = 0; i < result.Length; i++) {
7 int totalShift = 0;
8 for (int j = 0; j <= i; j++) {
9 totalShift += shifts[j];
10 }
11 totalShift %= 26;
12 result[i] = (char)((result[i] - 'a' + totalShift) % 26 + 'a');
13 }
14 return new string(result);
15 }
16
17 static void Main() {
18 string s = "abc";
19 int[] shifts = { 3, 5, 9 };
20 Console.WriteLine(ShiftingLetters(s, shifts));
21 }
22}
This C# solution involves string manipulation through character arrays, updating each character based on cumulative shift computations.
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)
.
1def
Python's solution effectively combines cumulative shift calculation in a single backward loop for optimized processing.