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.
1using System;
2
3public class Solution {
4 public static void ReverseString(char[] s, int k) {
5 for (int start = 0; start < s.Length; start += 2 * k) {
6 int i = start, j = Math.Min(start + k - 1, s.Length - 1);
7 while (i < j) {
8 char temp = s[i];
9 s[i++] = s[j];
10 s[j--] = temp;
11 }
12 }
13 }
14
15 public static void Main() {
16 string str = "abcdefg";
17 char[] s = str.ToCharArray();
18 int k = 2;
19 ReverseString(s, k);
20 Console.WriteLine(new String(s)); // Output: "bacdfeg"
21 }
22}
This C# program utilizes an in-place string reversal using character arrays. Handling ranges manually ensures we control the reversal mechanism for each 2k segment efficiently.
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.