Problem Description
Given a string s and an integer array shifts of the same length, for each shifts[i] we shift the first i+1 letters of s by x times (cyclically advancing each letter). The task is to compute and return the final string after applying all shifts.
Key Insights
- Shifting a letter means moving to the next letter in the alphabet with wrap-around from 'z' to 'a'.
- Instead of applying shifts from the beginning each time, it is efficient to process the shifts in reverse order to compute cumulative shifts.
- Using a running suffix sum allows us to know how much each letter should ultimately be shifted.
- Modulo operation is key since shifting 26 times results in the same letter.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because we traverse the array once. Space Complexity: O(n) if creating a new array for the output. It can be optimized to O(1) additional space if updating in place (excluding the output).
Solution
We solve the problem using a reverse traversal of the shifts array to accumulate the total shifts for each character. By iterating from the end index towards the beginning, we compute a running total. As we process each character, we apply the shift modulo 26 (the number of letters in the alphabet) and update the character accordingly. This method avoids the repeated shifting of the same prefix and makes the solution efficient.