LeetCode //C - 848. Shifting Letters
848. Shifting Letters
You are given a string s of lowercase English letters and an integer array shifts of the same length.
Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that ‘z’ becomes ‘a’).
- For example, shift(‘a’) = ‘b’, shift(‘t’) = ‘u’, and shift(‘z’) = ‘a’.
Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.
Return the final string after all such shifts to s are applied.
Example 1:
Input: s = “abc”, shifts = [3,5,9]
Output: “rpl”
Explanation: We start with “abc”.
After shifting the first 1 letters of s by 3, we have “dbc”.
After shifting the first 2 letters of s by 5, we have “igc”.
After shifting the first 3 letters of s by 9, we have “rpl”, the answer.
Example 2:
Input: s = “aaa”, shifts = [1,2,3]
Output: “gfd”
Constraints:
- 1<=s.length<=1051 <= s.length <= 10^51<=s.length<=105
- s consists of lowercase English letters.
- shifts.length == s.length
- 0<=shifts[i]<=1090 <= shifts[i] <= 10^90<=shifts[i]<=109
From: LeetCode
Link: 848. Shifting Letters
Solution:
Ideas:
-
Each shifts[i] means: shift the first i+1 letters of s by shifts[i].
-
Instead of applying each shift step by step (which would be O(n²)), we compute the total shift contribution for each character from the end.
-
Observation:
- The last character (s[n-1]) is shifted by shifts[n-1].
- The second-to-last (s[n-2]) is shifted by shifts[n-2] + shifts[n-1].
- In general, character s[i] is shifted by the sum of all shifts from i to n-1.
-
Use modulo 26 (% 26) because shifting by multiples of 26 returns to the same character.
Code:
char* shiftingLetters(char* s, int* shifts, int shiftsSize) {long long total = 0; // use long long because shifts[i] can be up to 1e9int n = shiftsSize;// Traverse from end to startfor (int i = n - 1; i >= 0; i--) {total = (total + shifts[i]) % 26; // keep mod 26 to prevent overflows[i] = ((s[i] - 'a' + total) % 26) + 'a';}return s;
}