Skip to main content

Shifting Letters - Solution & Explanation

MediumArrayStringPrefix Sum13 min readAsked at: Microsoft, Google, Bloomberg
Practice this problem

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').

  • For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.

Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.

Return the final string after all such shifts to s are applied.

 

Example 1:

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.

Example 2:

Input: s = "aaa", shifts = [1,2,3]
Output: "gfd"

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
  • shifts.length == s.length
  • 0 <= shifts[i] <= 109

Approach Overview

Problem Overview: You are given a lowercase string s and an array shifts. Each shifts[i] means the first i + 1 characters of the string should be shifted forward in the alphabet that many times (wrapping around after 'z'). The task is to apply all operations and return the final string.

Approach 1: Naive Prefix Simulation (O(n²) time, O(1) space)

The straightforward idea is to process every shift operation directly. For each index i, iterate from the start of the string to i and shift every character by shifts[i]. Character shifting is done with modular arithmetic using (char - 'a' + shift) % 26. While simple to reason about, this repeatedly updates the same characters and leads to quadratic work. With large inputs, this approach quickly becomes too slow.

Approach 2: Cumulative Shift Calculation (O(n) time, O(n) space)

Each character s[i] is affected by all shift values from i to the end of the array. Instead of applying operations one by one, compute a cumulative suffix sum of the shifts array. Create a prefix-sum style structure where totalShift[i] = shifts[i] + shifts[i+1] + .... Then update each character once using totalShift[i] % 26. This removes repeated work and converts the problem into a single pass over the string. The technique is a classic use of prefix sum logic applied to a array while transforming a string.

Approach 3: Optimized Backward Calculation (O(n) time, O(1) space)

The cumulative idea can be implemented without an extra array. Traverse the string from right to left while maintaining a running shift value. At each step, update runningShift = (runningShift + shifts[i]) % 26, then apply that shift to s[i]. Because every character depends on all shifts to its right, this backward traversal naturally accumulates the correct value. Each character is processed exactly once, and no additional storage is required beyond a few variables.

Recommended for interviews: Interviewers typically expect the backward cumulative solution. The naive simulation demonstrates understanding of the problem mechanics, but the optimized O(n) solution shows you recognize overlapping operations and can compress them using cumulative sums. Implementing the backward pass with modular arithmetic is both efficient and clean.

Approach 1: Cumulative Shift Calculation

In this approach, we calculate the cumulative shift for each character and apply it directly. We start from the first character and compute the required shift by summing all applicable shift values for each character position. After calculating the cumulative shift, we adjust each character in the string accordingly.

This C implementation calculates the total shift for each character by iterating through the shift array and performs letter shifting using ASCII manipulations. Remember, we're cumulatively adjusting the character based on all previous shifts.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) where n is the length of the string due to the nested loops.
Space Complexity: O(1) since no extra space other than for variables is used.

Try this approach in the editor →

Approach 2: Optimized Backward Calculation

This approach optimizes the shift of letters by computing the cumulative shift from the last character to the first. It reduces the overhead of multiple summations using a single pass through the shifts array from back to front.

This C code optimizes the shift calculations by continuously adding shifts from right to left, which avoids recalculating sums repeatedly.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), processing each character once.
Space Complexity: O(1).

Try this approach in the editor →

Approach 3: Suffix Sum

For each character in the string s, we need to calculate its final shift amount, which is the sum of shifts[i], shifts[i + 1], shifts[i + 2], and so on. We can use the concept of suffix sum, traversing shifts from back to front, calculating the final shift amount for each character, and then taking modulo 26 to get the final character.

The time complexity is O(n), where n is the length of the string s. Ignoring the space consumption of the answer, the space complexity is O(1).

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Cumulative Shift Calculation

Time Complexity: O(n^2) where n is the length of the string due to the nested loops.
Space Complexity: O(1) since no extra space other than for variables is used.

Optimized Backward Calculation

Time Complexity: O(n), processing each character once.
Space Complexity: O(1).

Suffix Sum—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Naive Prefix SimulationO(n²)O(1)Useful for understanding the shifting process or very small inputs
Cumulative Shift CalculationO(n)O(n)When using explicit prefix/suffix sum arrays for clarity
Optimized Backward CalculationO(n)O(1)Best production and interview solution with minimal memory usage

Video Solution

Leetcode - Shifting Letters (Python) • Timothy H Chang • 9,642 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Shifting Letters easy or hard?
Shifting Letters is considered a medium-level problem. The main difficulty comes from recognizing that each shift affects all earlier characters. Once you realize the overlapping operations can be combined using cumulative sums, the implementation becomes straightforward.
Shifting Letters Python/Java solution
In Python or Java, the optimal implementation iterates from the end of the string while accumulating shift values modulo 26. Convert characters to numeric offsets using 'a', apply the shift, then convert back to characters. Both languages achieve O(n) time complexity with constant extra space.
How to solve Shifting Letters in O(n)?
Compute the cumulative shift while traversing from right to left. Maintain a variable runningShift and update it as runningShift = (runningShift + shifts[i]) % 26. Apply that shift to s[i] using modular arithmetic. This avoids repeated updates and transforms the problem into a single linear pass.
What is the best approach for Shifting Letters?
The optimized backward cumulative shift approach is the best solution. Traverse the string from right to left while maintaining a running shift value. Each step adds shifts[i] to the running total and applies it modulo 26 to the character. This processes every character once with O(n) time and O(1) extra space.
Is Shifting Letters asked at Google/Amazon/Meta?
Shifting Letters represents a common interview pattern involving prefix sums and string manipulation. Variations of cumulative operations on arrays or strings appear frequently in interviews at companies like Amazon, Google, and Meta, especially in medium-level coding rounds.
What data structure is used in Shifting Letters?
The problem primarily uses arrays and strings along with prefix-sum style cumulative calculations. No advanced data structures are required. Efficient solutions rely on modular arithmetic and maintaining a running suffix sum while iterating through the array.
What is the time complexity of Shifting Letters?
The optimal solution runs in O(n) time where n is the length of the string. Each character is visited exactly once while accumulating the shift values. The naive simulation approach takes O(n^2) because each shift operation repeatedly modifies earlier characters.

Ready to solve this problem?

Practice Shifting Letters with our built-in code editor and test cases.

Practice on FleetCode