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
Shifting Letters II - Optimal Solution INPUT String s = "abc" a idx 0 b idx 1 c idx 2 shifts array: [0, 1, 1] forward 0-1 [1, 2, 0] backward 1-2 [0, 2, 1] forward 0-2 dir=1: forward (+1) dir=0: backward (-1) wrap: z--a, a--z ALGORITHM STEPS 1 Difference Array diff[n+1] for range updates 2 Mark Boundaries diff[start]+=d, diff[end+1]-=d Building diff array: +2 [0] 0 [1] -1 [2] -1 [3] 3 Prefix Sum Get total shifts per index Net shifts: +2 idx 0 +2 idx 1 +1 idx 2 4 Apply Shifts char = (c + shift) % 26 FINAL RESULT Character Transformations: a +2 --> a (0+2)%26=2 b +2 --> c (1+2)%26=3 c +1 --> e (2+1)%26=4 Output: "ace" OK - Verified Key Insight: Use Difference Array technique to avoid O(n) updates per shift operation. Mark start with +d and end+1 with -d, then compute prefix sum for net shifts. Time: O(n + m) where n=string length, m=shifts count | Space: O(n) TutorialsPoint - Shifting Letters II | Difference Array Approach
Asked in
Google 25 Amazon 18 Facebook 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen