Shifting Letters II Problem
Description
LeetCode Problem 2381.
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [start_i, end_i, direction_i]. For every i, shift the characters in s from the index start_i to the index end_i (inclusive) forward if direction_i = 1, or shift the characters backward if direction_i = 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.
Example 1:
Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
Output: "ace"
Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".
Example 2:
Input: s = "dztz", shifts = [[0,0,0],[1,1,1]]
Output: "catz"
Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".
Constraints:
1 <= s.length, shifts.length <= 5 * 10^4shifts[i].length == 30 <= start_i <= end_i < s.length0 <= direction_i <= 1sconsists of lowercase English letters.
Solution
Approach: Difference Array
Treat a forward shift as +1 and a backward shift as -1. A shift on [l, r] becomes two updates on a difference array d: add the value at l and subtract it at r + 1.
After all shifts are recorded, a prefix sum over d gives the net shift of every position. Apply it to each letter modulo 26, adding 26 first so the result is never negative.
Complexity: time O(n + m), space O(n), where n is the length of s and m is the number of shifts.
class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
n = len(s)
d = [0] * (n + 1)
for i, j, v in shifts:
if v == 0:
v = -1
d[i] += v
d[j + 1] -= v
for i in range(1, n + 1):
d[i] += d[i - 1]
return ''.join(
chr(ord('a') + (ord(s[i]) - ord('a') + d[i] + 26) % 26) for i in range(n)
)