Given a string and an integer k, you need to reverse the first k characters for every segment of length 2k characters counting from the start of the string. If there are less 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 left the other as original.
Example
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
In the above example, the first chunk of two "ab" was reversed to "ba" and the third chunk of two "ef" was reversed to "fe".
This is my approach:
var reverseStr = function(s, k) {
for (let i = 0; i < k; i++) {
let temp = s[i];
s[i] = s[k - i - 1];
s[k - i - 1] = temp
}
return s
};
console.log(reverseStr("abcdefg", 2))
How do I produce the desired output?