Sponsored
Sponsored
In this approach, we directly manipulate the string representation by considering it as a character array (or list in some languages) for in-place modification. We handle the string in chunks of 2k and reverse the first k characters of each chunk.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we are reversing in place.
1function reverseString(s, k) {
2 s = s.split('');
3 for (let start = 0; start < s.length; start += 2 * k) {
4 let i = start, j = Math.min(start + k - 1, s.length - 1);
5 while (i < j) {
6 [s[i], s[j]] = [s[j], s[i]];
7 i++;
8 j--;
9 }
10 }
11 return s.join('');
12}
13
14let s = "abcdefg";
15let k = 2;
16console.log(reverseString(s, k)); // Output: "bacdfeg"
This JavaScript solution operates by splitting the string into an array, enabling in-place manipulation. The approach uses destructuring assignments for efficient character swapping within designated segments.
In this approach, we use a StringBuilder (or equivalent structure in the respective programming languages) to construct the final output. This approach is effective because handling mutable strings directly supports efficient character manipulation operations.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1) as we operate directly on the input array.
1#include <string>
#include <algorithm>
std::string reverseString(const std::string& s, int k) {
std::string result = s;
for (size_t start = 0; start < result.size(); start += 2 * k) {
auto end = std::min(start + k, result.size());
std::reverse(result.begin() + start, result.begin() + end);
}
return result;
}
int main() {
std::string s = "abcdefg";
int k = 2;
std::cout << reverseString(s, k); // Output: "bacdfeg"
return 0;
}
This C++ solution leverages std::string
directly, while using std::reverse
for inversion within calculated bounds of the current target chunk. This simplifies the logic by letting STL handle lower-level operations.