Shifting Letters - Problem

You are given a string s of lowercase English letters and an integer array shifts of the same length.

Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.

Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.

Return the final string after all such shifts to s are applied.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
💡 Note: Position 0 ('a') gets shifted 3+5+9=17 times: a→r. Position 1 ('b') gets shifted 5+9=14 times: b→p. Position 2 ('c') gets shifted 9 times: c→l.
Example 2 — Single Character
$ Input: s = "z", shifts = [25]
Output: "y"
💡 Note: The character 'z' is shifted 25 times. Since z+25 wraps around, z→y (25 shifts from z brings us to y).
Example 3 — Wrapping Around
$ Input: s = "aaa", shifts = [1,2,3]
Output: "gfd"
💡 Note: Position 0: a + (1+2+3)=6 shifts → g. Position 1: a + (2+3)=5 shifts → f. Position 2: a + 3 shifts → d.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters
  • shifts.length == s.length
  • 0 ≤ shifts[i] ≤ 109

Visualization

Tap to expand
Shifting Letters - Optimal Solution INPUT String s = "abc" 'a' i=0 'b' i=1 'c' i=2 shifts = [3, 5, 9] 3 5 9 Each shifts[i] affects first (i+1) characters shifts[0]=3: shift s[0] shifts[1]=5: shift s[0..1] shifts[2]=9: shift s[0..2] ALGORITHM STEPS 1 Compute Total Shifts Calculate cumulative sum from right to left 2 Suffix Sum Array total[i] = sum(shifts[i..n-1]) 17 3+5+9 14 5+9 9 9 3 Apply Modulo 26 17%26=17, 14%26=14, 9%26=9 4 Shift Each Character 'a'+17='r', 'b'+14='p' 'c'+9='l' (char - 'a' + shift) % 26 + 'a' wrap around at 'z' FINAL RESULT Output: "rpl" 'r' 'p' 'l' Calculation Details: 'a'(0) + 17 = 17 --> 'r' 'b'(1) + 14 = 15 --> 'p' 'c'(2) + 9 = 11 --> 'l' Complexity: Time: O(n) Space: O(1) extra OK Key Insight: Instead of applying each shift operation separately (O(n^2)), compute the total shifts for each position using suffix sums. Character at index i receives shifts[i] + shifts[i+1] + ... + shifts[n-1] total shifts. This reduces time complexity from O(n^2) to O(n) by processing right-to-left with running sum. TutorialsPoint - Shifting Letters | Optimal Solution (Suffix Sum Approach)
Asked in
Google 15 Facebook 12
89.7K Views
Medium Frequency
~15 min Avg. Time
1.2K 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