Shifting Letters II - 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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abc", shifts = [[0,1,1],[1,2,0],[0,2,1]]
›
Output:
"ccc"
💡 Note:
Using difference array: [0,1,1] adds +2 at pos 0, -1 at pos 1, -1 at pos 2. After [1,2,0]: +2 at pos 0, -2 at pos 1, -1 at pos 2, +1 at pos 3. After [0,2,1]: +3 at pos 0, -2 at pos 1, -2 at pos 2, +0 at pos 3. Prefix sums: [3,1,0] giving shifts of +3,+1,+0 → 'a'+3='d' but with modulo gives 'a'→'d', 'b'→'c', 'c'→'c'. Actually: net shifts are [+2,+1,+0] → 'c','c','c'.
Example 2 — Single Character
$
Input:
s = "a", shifts = [[0,0,1]]
›
Output:
"b"
💡 Note:
Single shift forward: 'a' becomes 'b'
Example 3 — Wrap Around
$
Input:
s = "z", shifts = [[0,0,1]]
›
Output:
"a"
💡 Note:
Forward shift from 'z' wraps around to 'a'
Constraints
- 1 ≤ s.length ≤ 5 × 104
- 1 ≤ shifts.length ≤ 5 × 104
- shifts[i].length = 3
- 0 ≤ starti ≤ endi < s.length
- directioni is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code