Shifting Letters - Problem
Transform letters through cascading shifts!
You are given a string
How shifting works:
• Each letter shifts to the next letter in the alphabet (wrapping around: 'z' → 'a')
•
The Challenge:
For each
Goal: Return the final string after all shift operations are applied.
Example: If
• First operation: shift first 1 letter 3 times: "abc" → "dbc"
• Second operation: shift first 2 letters 5 times: "dbc" → "igc"
• Third operation: shift first 3 letters 9 times: "igc" → "rpl"
You are given a string
s of lowercase English letters and an integer array shifts of the same length. Your task is to perform a series of cascading shifts on the string.How shifting works:
• Each letter shifts to the next letter in the alphabet (wrapping around: 'z' → 'a')
•
shift('a') = 'b', shift('t') = 'u', shift('z') = 'a'The Challenge:
For each
shifts[i] = x, you need to shift the first i+1 letters of the string x times. This creates a cascading effect where earlier letters get shifted multiple times by later operations.Goal: Return the final string after all shift operations are applied.
Example: If
s = "abc" and shifts = [3,5,9]:• First operation: shift first 1 letter 3 times: "abc" → "dbc"
• Second operation: shift first 2 letters 5 times: "dbc" → "igc"
• Third operation: shift first 3 letters 9 times: "igc" → "rpl"
Input & Output
example_1.py — 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.py — Single Character
$
Input:
s = "z", shifts = [25]
›
Output:
"y"
💡 Note:
The character 'z' is shifted 25 times. Since there are 26 letters, 25 shifts brings 'z' to 'y' (wrapping around the alphabet).
example_3.py — Large Shifts
$
Input:
s = "aaa", shifts = [1,2,3]
›
Output:
"gfd"
💡 Note:
Position 0 gets 1+2+3=6 shifts: 'a'→'g'. Position 1 gets 2+3=5 shifts: 'a'→'f'. Position 2 gets 3 shifts: 'a'→'d'.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters
- shifts.length == s.length
- 0 ≤ shifts[i] ≤ 109
- Note: Large shift values require modulo arithmetic to avoid overflow
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Each position gets affected by all shift operations from that position onwards
2
Calculate Cumulative Effect
Work backwards to efficiently compute total shifts per position
3
Apply Once
Apply the calculated total shifts to each character in a single pass
Key Takeaway
🎯 Key Insight: Instead of repeatedly applying shifts (domino effect), calculate the total shifts each position will receive by working backwards, then apply once. This transforms an O(n²) problem into an elegant O(n) solution using the prefix sum technique.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code