Reverse String II Problem
Description
LeetCode Problem 541.
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
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 left the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
- 1 <= s.length <= 10^4
- s consists of only lowercase English letters.
- 1 <= k <= 10^4
Solution
Approach: Reverse Every Other Block of k
Split the string into blocks of 2k characters. In each block only the first k characters are reversed, and the rest stays as it is. The blocks start at indices 0, 2k, 4k, ..., so a single loop with step 2k visits them all:
- Copy the string into a character array (strings are immutable in most languages).
- For each
startin0, 2k, 4k, ..., reverse the characters fromleft = starttoright = min(start + k, n) - 1with two pointers that swap and move toward each other. - Join the characters back into a string.
For s = "abcdefg", k = 2, the blocks are abcd, efg; reversing the first two of each gives ba cd, fe g, so the result is "bacdfeg".
The two special cases in the statement are both handled by the min. With fewer than k characters left, right is the last index, so all of them are reversed. With between k and 2k left, right = start + k - 1 as usual and the rest is never touched. The common bug is computing right = start + k - 1 without the min, which runs past the end of the string in the last block.
Complexity: O(n) time, since each character is swapped at most once, and O(n) space for the character array, where n is the length of s.
class Solution:
def reverseStr(self, s: str, k: int) -> str:
chars = list(s)
# Each block of 2k characters starts at a multiple of 2k; reverse the first k of it.
for start in range(0, len(chars), 2 * k):
left = start
right = min(start + k, len(chars)) - 1 # fewer than k left: reverse all of them
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return "".join(chars)