Leetcode 848: Shifting Letters

grid47
grid47
Exploring patterns and algorithms
Aug 14, 2024 5 min read

You are given a string s of lowercase English letters and an array shifts, where shifts[i] represents the number of times to shift the first i + 1 characters of s. The shift operation for a letter means moving to the next letter in the alphabet, and if the letter is ‘z’, it wraps around to ‘a’. After applying all the shifts, return the final string.
Problem
Approach
Steps
Complexity
Input: You are given a string `s` consisting of lowercase English letters and an integer array `shifts` of the same length. Each element of `shifts[i]` represents how many times you need to shift the first `i + 1` letters of `s`.
Example: Input: s = 'abc', shifts = [3, 5, 9]
Constraints:
• 1 <= s.length <= 10^5
• s consists of lowercase English letters.
• shifts.length == s.length
• 0 <= shifts[i] <= 10^9
Output: Return the final string after applying all the shifts to `s` as specified by the array `shifts`.
Example: Output: 'rpl'
Constraints:
• The final string is derived by applying the shifts progressively to the characters of `s`.
Goal: The goal is to compute the final string after applying all the shifts to the string `s`.
Steps:
• Step 1: Process the shifts array by calculating cumulative shifts from the end of the string towards the beginning.
• Step 2: For each character in `s`, apply the shift operation by moving the character forward in the alphabet by the corresponding number of shifts (considering the wrap-around).
• Step 3: Return the resulting string after all shifts have been applied.
Goal: Ensure that the solution handles the problem constraints efficiently, especially with large input sizes.
Steps:
• The array `shifts` and the string `s` will always have the same length.
• The shifts array will contain values between 0 and 10^9, so operations must handle large values efficiently.
Assumptions:
• The string `s` contains only lowercase English letters.
• The length of the string `s` and the array `shifts` will always match.
Input: Input: s = 'abc', shifts = [3, 5, 9]
Explanation: Initially, the string is 'abc'. After shifting the first 1 letter by 3, it becomes 'dbc'. Then, shifting the first 2 letters by 5 results in 'igc'. Finally, shifting the first 3 letters by 9 gives 'rpl'. Hence, the final result is 'rpl'.

Input: Input: s = 'aaa', shifts = [1, 2, 3]
Explanation: The string starts as 'aaa'. After shifting the first 1 letter by 1, it becomes 'b'. Then, shifting the first 2 letters by 2 gives 'd'. Finally, shifting the first 3 letters by 3 results in 'gfd'. Thus, the final result is 'gfd'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus