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 <stdio.h>
2#include <string.h>
3
4void reverseString(char* s, int k) {
5 int length = strlen(s);
6 for (int start = 0; start < length; start += 2 * k) {
7 int i = start, j = (start + k - 1 < length) ? start + k - 1 : length - 1;
8 while (i < j) {
9 // Swap characters
10 char temp = s[i];
11 s[i++] = s[j];
12 s[j--] = temp;
13 }
14 }
15}
16
17int main() {
18 char s[] = "abcdefg";
19 int k = 2;
20 reverseString(s, k);
21 printf("%s", s); // Output: "bacdfeg"
22 return 0;
23}
This C program utilizes a function reverseString
which modifies the string s
in place. It processes segments of length 2k
, reversing the first k
characters within each segment. The main function demonstrates an example with s = "abcdefg"
and k = 2
.
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 C solution defines a helper function reverseSubString
to serve reversal needs within the limits of given indices. The main logic within reverseString
iterates over character chunks and utilizes this helper for targeted manipulation.