Problem
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').
Return the final string after all such shifts to s are applied.
Examples
Example 1
| |
Example 2
| |
Constraints
1 <= s.length, shifts.length <= 5 * 104shifts[i].length == 30 <= starti <= endi < s.length0 <= directioni <= 1sconsists of lowercase English letters.
Solution
Method 1 - Diffs with Prefix Sum
Here is the approach:
- Initialisation of the Difference Array:
- Create a difference array
diffof the same length as the stringsand initialise it with zeroes. - For each shift operation, update the start and end indices of the
diffarray based on the direction (forward or backward shift).
- Create a difference array
- Applying the Shifts:
- Traverse through the
shiftsarray. - If
directioni == 1, increasediff[starti]by 1 and decreasediff[endi + 1]by 1. - If
directioni == 0, decreasediff[starti]by 1 and increasediff[endi + 1]by 1.
- Traverse through the
- Creating the Final Shift Pattern:
- Convert the
diffarray into a cumulative sum array to get the net shift at each character index.
- Convert the
- *Applying the Shifts to the String:
- Traverse through the string
sand apply the calculated shifts. Wrap around using modulo operation for alphabetic shifts.
- Traverse through the string
- Finalize the Result:
- Construct the final string from the updated characters.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + m)wherenis the length of the stringsandmis the number of shifts. - 🧺 Space complexity:
O(n), mainly for the difference array.