MediumNo. 2381

Shifting Letters II — LeetCode 2381 Python Solution

Pattern
Prefix Sum
Topics
Array, String, Prefix Sum
Reading time
3 min

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.