Reverse String II(#541)
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"
Input: s = "abcd", k = 2
Output: "bacd"
๐ง Approach
โข 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 handle boundary conditions safely.
โข Finally, join the array and return the result.
๐ป Code
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.