KatInterview

878. Shifting Letters

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to shift letters of a string s based on values in an array shifts. For each shifts[i], we must shift the first i+1 letters of s. A key observation is that a character s[j] is affected by every shift shifts[i] where j <= i. Therefore, the total shift for s[j] is the sum of all shifts[k] for k from j to the end of the array.

Solution

Shifting Letters in Python

class Solution:
    def shiftingLetters(self, s: str, shifts: List[int]) -> str:
        n = len(s)
        # Convert string to list of characters for mutable operations.
        res_chars = list(s)
        
        cumulative_shift = 0
        
        # Iterate from right to left to calculate suffix sums of shifts on the fly.
        for i in range(n - 1, -1, -1):
            # Add the current shift to the cumulative total.
            cumulative_shift += shifts[i]
            
            # Python's integers handle arbitrary size, so no overflow issues.
            
            # Get the original character's position (0-25).
            original_pos = ord(res_chars[i]) - ord('a')
            
            # Apply the total shift, wrapping around the alphabet using modulo 26.
            new_pos = (original_pos + cumulative_shift) % 26
            
            # Update the character in our list.
            res_chars[i] = chr(ord('a') + new_pos)
            
        # Join the list of characters back into a string.
        return "".join(res_chars)

Shifting Letters in Java

class Solution {
    public String shiftingLetters(String s, int[] shifts) {
        int n = s.length();
        char[] chars = s.toCharArray();
        
        // The total shift for any character is the sum of shifts to its right, including itself.
        // We can compute this by iterating from right to left.
        int cumulative_shift = 0;
        
        for (int i = n - 1; i >= 0; i--) {
            // Add the current shift to the cumulative total. 
            // We use (shifts[i] % 26) to prevent potential integer overflow if shifts[i] is large,
            // though (cumulative_shift + shifts[i]) would likely not overflow an int since
            // cumulative_shift is always < 26.
            // The double modulo is mathematically sound: (a + b) % m == ((a % m) + (b % m)) % m.
            cumulative_shift = (cumulative_shift + shifts[i] % 26) % 26;
            
            // Get the original character's position (0-25).
            int original_pos = chars[i] - 'a';
            
            // Apply the total shift.
            int new_pos = (original_pos + cumulative_shift) % 26;
            
            // Update the character.
            chars[i] = (char)('a' + new_pos);
        }
        
        return new String(chars);
    }
}

Shifting Letters in C++

class Solution {
public:
    string shiftingLetters(string s, vector<int>& shifts) {
        // Use a long long to prevent overflow as cumulative shifts can be large.
        long long cumulative_shift = 0;
        int n = s.length();
        
        // Iterate from right to left.
        for (int i = n - 1; i >= 0; --i) {
            // Add the current shift to the cumulative total.
            cumulative_shift += shifts[i];
            
            // Calculate the original character's position (0-25).
            int original_pos = s[i] - 'a';
            
            // Apply the total shift, wrapping around the alphabet using modulo 26.
            int new_pos = (original_pos + cumulative_shift) % 26;
            
            // Update the character in the string.
            s[i] = 'a' + new_pos;
        }
        
        return s;
    }
};

Shifting Letters in TypeScript

function shiftingLetters(s: string, shifts: number[]): string {
    const n = s.length;
    // Split string into an array of characters for mutable operations.
    const chars = s.split('');

    let cumulative_shift = 0;

    // Iterate from right to left.
    for (let i = n - 1; i >= 0; i--) {
        // Add the current shift to the cumulative total, modulo 26.
        cumulative_shift = (cumulative_shift + shifts[i]) % 26;

        // Get the original character's code and its position (0-25).
        const original_code = chars[i].charCodeAt(0);
        const original_pos = original_code - 'a'.charCodeAt(0);

        // Apply the total shift.
        const new_pos = (original_pos + cumulative_shift) % 26;

        // Update the character in the array.
        chars[i] = String.fromCharCode('a'.charCodeAt(0) + new_pos);
    }

    // Join the array of characters back into a string.
    return chars.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.