Shifting Letters II — LeetCode 2381 Python Solution
- Problem
- #2381
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
- Output
- "ace"
- Explanation
- Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Python solution
class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
n = len(s)
d = [0] * (n + 1)
for i, j, v in shifts:
if v == 0:
v = -1
d[i] += v
d[j + 1] -= v
for i in range(1, n + 1):
d[i] += d[i - 1]
return ''.join(
chr(ord('a') + (ord(s[i]) - ord('a') + d[i] + 26) % 26) for i in range(n)
)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2381. Shifting Letters II 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 2381. Shifting Letters II?
- LeetCode 2381. Shifting Letters II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2381. Shifting Letters II?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2381. Shifting Letters II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2381. Shifting Letters II cover?
- LeetCode 2381. Shifting Letters II is tagged Array, String and Prefix Sum on LeetCode.