LeetCode 541: Reverse String II Solution
Master LeetCode problem 541 (Reverse String II), a easy 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.
541. Reverse String II
Problem Explanation
Explanation
To solve this problem, we can iterate over the string in steps of 2k, and for each group of k characters, we reverse the first k characters. If the remaining characters are less than k but greater than 0, we reverse all of them. We can achieve this by swapping characters from the start and end of the group of k characters until we reach the middle.
Time Complexity: O(n) where n is the length of the string s. Space Complexity: O(1) as we are not using any extra space other than a few variables.
Solution Code
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < s.length(); i += 2*k) {
int start = i;
int end = Math.min(i + k - 1, s.length() - 1);
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
return new String(chars);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 541 (Reverse String II)?
This page provides optimized solutions for LeetCode problem 541 (Reverse String 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 541 (Reverse String II)?
The time complexity for LeetCode 541 (Reverse String II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 541 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 541 in Java, C++, or Python.