Reverse String II
(#541), Easy
Category: String, Two Pointer
Problem Statement
You're given a string `s` and an integer `k`. The task is to reverse the first `k` characters for every `2k` characters, starting from the beginning of the string. Rules: 1. If there are fewer than `k` characters left, reverse all of them. 2. If there are at least `k` but fewer than `2k` characters, then reverse only the first `k`, and leave the rest as-is.
Examples
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Explanation: First block: "ab" → "ba", Second block: "ef" → "fe". Final string: "bacdfeg".
Input: s = "abcd", k = 2
Output: "bacd"
Explanation: Reverse first k = 2 → "ab" → "ba", rest stays same → "bacd".
Approach
Two Pointer Chunk Reversal
- Convert the string into a character array for easy in-place operations.
- Loop through the string in increments of `2k`.
- For each chunk, reverse the first `k` characters using two pointers.
- Use `Math.min(i + k - 1, s.length - 1)` to ensure we don't go out of bounds.
- After all chunks are processed, join the character array into a string and return.
var reverseStr = function(s, k) {
let arr = s.split('');
for (let i = 0; i < s.length; i += 2 * k) {
let left = i;
let right = Math.min(i + k - 1, s.length - 1);
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
return arr.join('');
};
Complexity
Time: O(n) – We iterate over the string once in chunks.
Space: O(n) – Due to character array manipulation.