Leetcode 2381: Shifting Letters II

grid47
grid47
Exploring patterns and algorithms
Mar 13, 2024 7 min read

You are given a string s consisting of lowercase English letters and a 2D array shifts. Each entry in the array represents a shift operation, where a segment of the string from starti to endi (inclusive) is shifted forward if directioni is 1, or backward if directioni is 0. A forward shift means replacing a character with the next letter in the alphabet (wrapping around from ‘z’ to ‘a’), and a backward shift means replacing a character with the previous letter (wrapping around from ‘a’ to ‘z’). You need to return the final string after all shifts are applied.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` of lowercase English letters and a 2D integer array `shifts` where each entry contains [starti, endi, directioni].
Example: s = 'abc', shifts = [[0, 1, 0], [1, 2, 1], [0, 2, 1]]
Constraints:
• 1 <= s.length, shifts.length <= 50000
• shifts[i].length == 3
• 0 <= starti <= endi < s.length
• 0 <= directioni <= 1
• s consists of lowercase English letters.
Output: Return the final string after applying all shifts as described in the problem.
Example: Output: 'ace'
Constraints:
Goal: The goal is to apply the shifts efficiently, ensuring the correct forward or backward shifting of characters based on the direction specified.
Steps:
• 1. Initialize an array to track the net shift at each index.
• 2. Iterate through the shifts array and update the net shifts at the corresponding start and end indices.
• 3. Calculate the cumulative shift for each character using the net shift array.
• 4. Apply the shifts to the string, taking care to wrap around alphabetically.
Goal: The string `s` will have a length between 1 and 50,000, and the number of shifts will also be between 1 and 50,000. Each shift operation will involve indices within the string length.
Steps:
• The length of the string `s` is between 1 and 50,000.
• The number of shifts is also between 1 and 50,000.
• Each character in `s` is a lowercase English letter.
Assumptions:
• The input string and shifts are valid and conform to the constraints.
Input: Input: s = 'abc', shifts = [[0, 1, 0], [1, 2, 1], [0, 2, 1]]
Explanation: First, shift the characters from index 0 to 1 backward ('a' becomes 'z', 'b' becomes 'a'). Now s = 'zac'. Next, shift the characters from index 1 to 2 forward ('a' becomes 'b'). Now s = 'zbd'. Finally, shift the characters from index 0 to 2 forward ('z' becomes 'a', 'b' becomes 'c'). Now s = 'ace'.

Input: Input: s = 'dztz', shifts = [[0, 0, 0], [1, 1, 1]]
Explanation: First, shift the character at index 0 backward ('d' becomes 'c'). Now s = 'cztz'. Next, shift the character at index 1 forward ('z' becomes 'a'). Now s = 'catz'.

Link to LeetCode Lab


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