408. Reverse String II
You receive a string s and a positive integer k. Sweep the string in blocks of 2k characters, and inside each block flip the first k characters while leaving the second k alone.
The tail of the string may not fill a whole block, so two tie-breaking rules apply to whatever is left at the end:
- Fewer than
kcharacters remain → reverse all of them. - At least
kbut fewer than2kremain → reverse the firstk, keep the rest untouched.
Return the transformed string.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Explanation: Block "abcd": reverse "ab" → "ba", keep "cd". The tail "efg" has at least k = 2 characters, so reverse "ef" → "fe" and keep "g".
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Explanation: One full block "abcd": its first two characters flip to "ba" and "cd" stays put.
Constraints:
- 1 ≤ s.length ≤ 10⁴
- s consists of lowercase English letters only
- 1 ≤ k ≤ 10⁴
Hints:
Picking the blocks needs no cleverness: they start at indices 0, 2k, 4k, … — a for-loop with step 2k.
For a block starting at i, the segment to reverse runs from i to min(i + k, n) − 1. That single min() implements both tail rules at once.
To reverse a segment in place, swap characters from both ends with two pointers that walk toward each other.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "abcdefg", k = 2
Expected output: "bacdfeg"