Shifting Letters — LeetCode 848 Python Solution
- Problem
- #848
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The 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').
Example
- Input
- s = "abc", shifts = [3,5,9]
- Output
- "rpl"
- Explanation
- We start with "abc".
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 848. Shifting Letters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 848. Shifting Letters?
- LeetCode 848. Shifting Letters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 848. Shifting Letters?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 848. Shifting Letters?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 848. Shifting Letters cover?
- LeetCode 848. Shifting Letters is tagged Array, String and Prefix Sum on LeetCode.