MediumNo. 0848

Shifting Letters — LeetCode 848 Python Solution

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

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

PythonSolution
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

Time
O(n)where n is the length of the string s
Space · auxiliary
O(1)

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.

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.