Reverse String II
Problem
For every 2k characters of s starting from the beginning, reverse the first k characters. If fewer than k remain, reverse all of them. If between k and 2k remain, reverse the first k and leave the rest as-is.
s = "abcdefg", k = 2"bacdfeg"def reverse_str(s, k):
arr = list(s)
for i in range(0, len(arr), 2 * k):
arr[i:i + k] = reversed(arr[i:i + k])
return "".join(arr)
function reverseStr(s, k) {
const arr = s.split("");
for (let i = 0; i < arr.length; i += 2 * k) {
let lo = i, hi = Math.min(i + k - 1, arr.length - 1);
while (lo < hi) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
lo++; hi--;
}
}
return arr.join("");
}
class Solution {
public String reverseStr(String s, int k) {
char[] a = s.toCharArray();
for (int i = 0; i < a.length; i += 2 * k) {
int lo = i, hi = Math.min(i + k - 1, a.length - 1);
while (lo < hi) {
char t = a[lo]; a[lo] = a[hi]; a[hi] = t;
lo++; hi--;
}
}
return new String(a);
}
}
string reverseStr(string s, int k) {
for (int i = 0; i < (int)s.size(); i += 2 * k) {
int lo = i, hi = min(i + k - 1, (int)s.size() - 1);
while (lo < hi) { swap(s[lo], s[hi]); lo++; hi--; }
}
return s;
}
Explanation
The rule sounds fiddly — reverse the first k of every 2k characters — but it becomes simple once you realize you only need to visit the start of each 2k block and reverse a small window there.
We stride the loop by 2 * k, so i lands on 0, 2k, 4k, and so on. At each block we reverse the slice from i up to i + k - 1. The next k characters of the block are left untouched, which is exactly what the problem asks.
The edge cases fall out automatically. We clamp the right end with min(i + k - 1, n - 1), so if fewer than k characters remain we just reverse whatever is left, and if between k and 2k remain we still only flip the first k.
Each reversal is the standard two-pointer swap (lo and hi moving toward each other), and every character is touched once, so the work is linear.
Example: s = "abcdefg", k = 2. Block "abcd" → reverse first 2 → "bacd"; block "efg" → reverse first 2 → "feg". Result: "bacdfeg".