Leetcode•Sep 20, 2025
Reverse String II
Hazrat Ali
Leetcode
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"
Solution
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
const reverseStr = (s, k) => {
const arr = s.split('');
for (let i = 0; i < arr.length; i += 2 * k) {
reverse(arr, i, Math.min(i + k - 1, arr.length - 1));
}
return arr.join('');
};
const reverse = (arr, i, j) => {
while (i < j) [arr[i++], arr[j--]] = [arr[j], arr[i]];
};