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 * 104
shifts[i].length == 3
0 <= starti <= endi < s.length
0 <= directioni <= 1
s
consists of lowercase English letters.
Solution
Method 1 - Diffs with Prefix Sum
Here is the approach:
- Initialisation of the Difference Array:
- Create a difference array
diff
of the same length as the strings
and initialise it with zeroes. - For each shift operation, update the start and end indices of the
diff
array based on the direction (forward or backward shift).
- Create a difference array
- Applying the Shifts:
- Traverse through the
shifts
array. - 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
diff
array 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
s
and 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)
wheren
is the length of the strings
andm
is the number of shifts. - 🧺 Space complexity:
O(n)
, mainly for the difference array.