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:
"ace"
💡 Note:
First shift [0,1,1]: shift indices 0,1 forward → "bcc". Second shift [1,2,0]: shift indices 1,2 backward → "bab". Third shift [0,2,1]: shift indices 0,1,2 forward → "cbc". Wait, let me recalculate: applying difference array gives net shifts of [+1,+1,+1] → "bcd".
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
Understanding the Visualization
1
Input
String "abc" with shifts [[0,1,1],[1,2,0],[0,2,1]]
2
Process
Accumulate net shifts per position using difference array
3
Output
Apply accumulated shifts to get final string
Key Takeaway
🎯 Key Insight: Use difference array to efficiently accumulate multiple range updates in O(n+m) time instead of O(n×m)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code