Leetcode #848: Shifting Letters
In this guide, we solve Leetcode #848 Shifting Letters in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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').
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, String, Prefix Sum
Intuition
Range queries become simple once we precompute cumulative sums.
We can transform subarray conditions into prefix comparisons.
Approach
Compute prefix sums and use a map to find matching prefixes.
This avoids nested loops while keeping the logic clear.
Steps:
- Compute prefix sums.
- Use a map to find valid ranges.
- Update the answer.
Example
Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation: We start with "abc".
After shifting the first 1 letters of s by 3, we have "dbc".
After shifting the first 2 letters of s by 5, we have "igc".
After shifting the first 3 letters of s by 9, we have "rpl", the answer.
Python Solution
class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
n, t = len(s), 0
s = list(s)
for i in range(n - 1, -1, -1):
t += shifts[i]
j = (ord(s[i]) - ord('a') + t) % 26
s[i] = ascii_lowercase[j]
return ''.join(s)
Complexity
The time complexity is , where is the length of the string . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.