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.
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5void reverseString(std::string& s, int k) {
6 int n = s.size();
7 for (int start = 0; start < n; start += 2 * k) {
8 if (start + k <= n) {
9 std::reverse(s.begin() + start, s.begin() + start + k);
10 } else {
11 std::reverse(s.begin() + start, s.end());
12 }
13 }
14}
15
16int main() {
17 std::string s = "abcdefg";
18 int k = 2;
19 reverseString(s, k);
20 std::cout << s; // Output: "bacdfeg"
21 return 0;
22}
In this C++ solution, std::reverse
is used to reverse segments of strings efficiently. We iterate over the string with a step of 2k
and reverse the first k
characters when available. This approach leverages the simplicity of C++ STL.
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
This JavaScript implementation uses string slices and concatenation, targeting intervals for reversal processing. By handling chunks separately, the method integrates chunk-based transformations efficiently.