LeetCode 2381: Shifting Letters II Solution
Master LeetCode problem 2381 (Shifting Letters II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2381. Shifting Letters II
Problem Explanation
Explanation
To solve this problem, we can iterate through the shifts array in reverse order and keep track of the cumulative shifts for each character. We can then apply the final shift to each character in the string to get the result.
- Initialize a variable
shiftCountto store the cumulative shift count. - Iterate through the shifts array in reverse order.
- For each shift, update the
shiftCountby adding the difference betweenendiandstartimultiplied bydirectioni. - Iterate through the string
sin reverse order. - For each character, calculate the new character after applying the cumulative shift.
- Update the character in the string
s. - Return the final string
s.
Solution Code
class Solution {
public String shiftingLetters(String s, int[][] shifts) {
int n = s.length();
long shiftCount = 0;
for (int i = shifts.length - 1; i >= 0; i--) {
int start = shifts[i][0];
int end = shifts[i][1];
int direction = shifts[i][2];
shiftCount += (end - start + 1) * (long) direction;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int shift = (int) (shiftCount % 26);
char newChar = (char) ('a' + (c - 'a' + shift) % 26);
sb.append(newChar);
shiftCount -= shift;
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2381 (Shifting Letters II)?
This page provides optimized solutions for LeetCode problem 2381 (Shifting Letters II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2381 (Shifting Letters II)?
The time complexity for LeetCode 2381 (Shifting Letters II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2381 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2381 in Java, C++, or Python.