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.
1public class Main {
2 public static void reverseString(char[] s, int k) {
3 for (int start = 0; start < s.length; start += 2 * k) {
4 int i = start, j = Math.min(start + k - 1, s.length - 1);
5 while (i < j) {
6 char temp = s[i];
7 s[i++] = s[j];
8 s[j--] = temp;
9 }
10 }
11 }
12
13 public static void main(String[] args) {
14 String str = "abcdefg";
15 char[] s = str.toCharArray();
16 int k = 2;
17 reverseString(s, k);
18 System.out.println(new String(s)); // Output: "bacdfeg"
19 }
20}
This Java program defines the function reverseString
which modifies a char array in place. We choose char array for in-place update, making it effective and space-efficient.
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.