Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer than k
characters left, reverse all of them. If there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters and leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2 Output: "bacd"
Constraints:
1 <= s.length <= 104
s
consists of only lowercase English letters.1 <= k <= 104
This problem asks to reverse the first k
characters for every 2k
characters in a given string. Let's break down the solution using the Two Pointers approach.
Algorithm:
Iteration: We iterate through the string with a step size of 2k
. This ensures we process chunks of 2k
characters at a time.
Reversal: For each chunk, we reverse only the first k
characters. We use two pointers, l
(left) and r
(right), to achieve this reversal. l
starts at the beginning of the chunk, and r
starts at k-1
(the end of the first k
characters).
Boundary Check: The Math.min(i + k - 1, n - 1)
part handles cases where there are fewer than 2k
characters remaining at the end of the string. It ensures r
doesn't go out of bounds.
In-place Reversal: The reversal is done in-place. We swap characters at l
and r
, moving the pointers towards the middle until they cross.
Return Value: Finally, we convert the modified character array back into a string and return it.
Time Complexity Analysis:
The outer loop iterates through the string at most n/2k
times, where n
is the length of the string. The inner loop (reversal) iterates at most k
times for each chunk. Therefore, the overall time complexity is O(n), because the nested loops combined iterate through the string at most once. Even though it looks like O(n*k), k is a constant, so it can be simplified.
Space Complexity Analysis:
The space complexity depends on the implementation. The Python solution uses reversed()
which might create a temporary reversed iterator, but overall the space usage is proportional to the length of the string. Therefore, the space complexity is O(n) in the worst case. For other languages that use in place reversal (like the Java or C++ solution), the space complexity becomes O(1) as we are modifying the string in-place, without using extra space proportional to input size.
Code Examples (with detailed comments):
Python:
class Solution:
def reverseStr(self, s: str, k: int) -> str:
cs = list(s) # Convert string to list for mutability
n = len(cs) #Get the length of the string
for i in range(0, n, 2 * k): #Iterate with a step of 2k
left = i # left pointer
right = min(i + k - 1, n - 1) #right pointer with boundary check
while left < right: #Reversal using two pointers
cs[left], cs[right] = cs[right], cs[left]
left += 1
right -= 1
return "".join(cs) #Convert back to string
Java:
class Solution {
public String reverseStr(String s, int k) {
char[] cs = s.toCharArray(); // Convert to char array
int n = cs.length;
for (int i = 0; i < n; i += 2 * k) {
int left = i;
int right = Math.min(i + k - 1, n - 1); // Boundary check
while (left < right) { //In-place reversal
char temp = cs[left];
cs[left] = cs[right];
cs[right] = temp;
left++;
right--;
}
}
return new String(cs); //Convert back to string
}
}
The C++, Go, and TypeScript solutions follow a similar structure, employing in-place reversal using two pointers and handling boundary conditions efficiently. The core logic remains consistent across all the languages.