541. Reverse String II LeetCode Solution
In this guide, you will get 541. Reverse String II LeetCode Solution with the best time and space complexity. The solution to Reverse String II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Reverse String II solution in C++
- Reverse String II solution in Java
- Reverse String II solution in Python
- Additional Resources
Problem Statement of Reverse String II
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Example 1:
Input: s = “abcdefg”, k = 2
Output: “bacdfeg”
Example 2:
Input: s = “abcd”, k = 2
Output: “bacd”
Constraints:
1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104
Complexity Analysis
- Time Complexity: O(|\texttt{s}|k)
- Space Complexity: O(1)
541. Reverse String II LeetCode Solution in C++
class Solution {
public:
string reverseStr(string s, int k) {
for (size_t i = 0; i < s.length(); i += 2 * k) {
int l = i;
int r = min(i + k - 1, s.length() - 1);
while (l < r)
swap(s[l++], s[r--]);
}
return s;
}
};
/* code provided by PROGIEZ */
541. Reverse String II LeetCode Solution in Java
class Solution {
public String reverseStr(String s, int k) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2 * k) {
int l = i;
int r = Math.min(i + k - 1, sb.length() - 1);
while (l < r) {
sb.setCharAt(l, s.charAt(r));
sb.setCharAt(r, s.charAt(l));
++l;
--r;
}
}
return sb.toString();
}
}
// code provided by PROGIEZ
541. Reverse String II LeetCode Solution in Python
class Solution:
def reverseStr(self, s: str, k: int) -> str:
return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else ""
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.