Leetcode Problem 2381. Shifting Letters II

2381. Shifting Letters II

Leetcode Solutions

Prefix Sum Approach

  1. Initialize a prefix sum array shiftAmounts with a length of len(s) + 1.
  2. For each shift operation [start, end, direction] in shifts: a. If direction is 1 (forward), increment shiftAmounts[start] and decrement shiftAmounts[end + 1]. b. If direction is 0 (backward), decrement shiftAmounts[start] and increment shiftAmounts[end + 1].
  3. Compute the prefix sum of shiftAmounts to get the total shift amount for each character.
  4. Iterate through the string s and for each character: a. Calculate the new character index after applying the shift. b. If the index is negative, add 26 until it is positive. c. Convert the index back to a character and append it to the result string.
  5. Return the result string.
UML Thumbnail

Brute Force Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...