Reverse String II (LeetCode 541): Solution and Explanation
Cut the string into blocks of 2k characters. In every block reverse the first k characters and leave the next k alone. A short last block reverses whatever it has, up to k characters.
Intuition
The rule looks fiddly because of the special cases at the end, but every block behaves the same way: the window to reverse always starts at the block start and is at most k long.
Blocks start at 0, 2k, 4k and so on, so a loop with step 2k visits each block once. The only question per block is where the window ends, and that is min(start + k - 1, n - 1).
The two end-of-string rules from the statement both fall out of that min. If fewer than k characters remain, the window is cut at n - 1 and reverses everything. If between k and 2k remain, the window is a full k and the leftovers are simply never touched.
Approach: Two pointers inside each 2k block
- Turn the string into a character array so swaps are cheap.
- Loop
startover 0, 2k, 4k, ... while it is less than n. - Set
left = startandright = min(start + k - 1, n - 1). - While
left < right, swap the two characters and move both pointers inward. - Join the array back into a string and return it.
Step-by-step example
s = "abcdefg", k = 2
- Blocks have length 2k = 4, so they start at index 0 and index 4.
- Block at 0 is "abcd". The window is 0..1. Swap 'a' and 'b' to get "bacd". Indices 2..3 stay.
- Block at 4 is "efg", only 3 characters. The window is still 4..5 because 3 is at least k. Swap 'e' and 'f'.
- 'g' at index 6 is in the keep half and is not touched.
- The result is "bacdfeg".
Code: Python, Java, C++
1class Solution:
2 def reverseStr(self, s: str, k: int) -> str:
3 chars = list(s)
4 for start in range(0, len(chars), 2 * k):
5 left, right = start, min(start + k - 1, len(chars) - 1)
6 while left < right:
7 chars[left], chars[right] = chars[right], chars[left]
8 left += 1
9 right -= 1
10 return ''.join(chars)1class Solution {
2 public String reverseStr(String s, int k) {
3 char[] chars = s.toCharArray();
4 for (int start = 0; start < chars.length; start += 2 * k) {
5 int left = start, right = Math.min(start + k - 1, chars.length - 1);
6 while (left < right) {
7 char tmp = chars[left];
8 chars[left++] = chars[right];
9 chars[right--] = tmp;
10 }
11 }
12 return new String(chars);
13 }
14}1class Solution {
2public:
3 string reverseStr(string s, int k) {
4 int n = s.size();
5 for (int start = 0; start < n; start += 2 * k) {
6 int left = start, right = min(start + k - 1, n - 1);
7 while (left < right) {
8 swap(s[left++], s[right--]);
9 }
10 }
11 return s;
12 }
13};Time and space complexity
O(n)
Each block costs O(k) at most, and there are about n / 2k blocks, so every character is touched at most once.
O(n)
Strings are immutable in most languages, so the character array is a copy. C++ can reverse the string in place with O(1) extra space.
Other approaches
Slice and concatenate (time O(n), space O(n))
For each block, build the new piece as reversed(s[start:start+k]) + s[start+k:start+2k] and append it to the answer. It reads well and has the same complexity, but creates many small strings.
Library reverse on a range (time O(n), space O(1))
In C++ call std::reverse(s.begin() + start, s.begin() + min(start + k, n)) for each block. It is the same algorithm with the inner loop hidden in the standard library.
Common mistakes
- Stepping the loop by k instead of 2k. That reverses every chunk instead of every other one.
- Forgetting to clamp the window end to n - 1, which reads past the end of the array on the last block.
- Treating the two end cases separately with extra branches. The single min handles both.
- Concatenating strings inside the loop in Java or C#, which can turn the solution into O(n^2).
Frequently asked questions
What if k is larger than the string?
Then there is one block, the window is clamped to the whole string, and the answer is the full string reversed.
Why does the second half of each block need no code at all?
Those characters stay in place, and the next block starts at start + 2k, which jumps right over them.
How is this different from Reverse String?
Reverse String swaps from both ends of the whole array once. Here the same swap loop runs on many small windows, one per 2k block.