15% off all plans & roadmaps Use code
See plansReverse String II
- LeetCode 541
- Easy
- Two Pointers
- String Reversal
Updated
TL;DR: Reverse the first k characters of every block of 2k characters, and leave the rest of each block alone. Walk the blocks with a step of 2k. Swap inward with two pointers whose right end is clamped to the string length.
Problem
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 fewer than k characters are left at the end, reverse all of them. If the last part has at least k but fewer than 2k characters, reverse its first k characters and leave the rest as it is.
Example 1
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Example 2
Input: s = "abcd", k = 2 Output: "bacd"
Constraints
1 <= s.length <= 10^4sconsists of only lowercase English letters.1 <= k <= 10^4
Constraints that matter
- n up to 10^4 means a single pass is cheap. Nothing here needs more than linear time, and O(n) extra memory is acceptable.
- Python, Java, JavaScript, Go and C# strings are immutable. You must copy the text into a list, array or byte slice before you can swap characters.
- k up to 10^4 can be larger than n. Then the step of 2k jumps past the end, so the right boundary must be clamped with a min and the loop must stop cleanly.
- k can be 1. Each block then reverses one character, which changes nothing. Your code should handle this without a special case.
Hints
Hint 1
This problem is a set of independent segment reversals.
Hint 2
A beginner splits the string into chunks and builds a new string.
Solution
Intuition
This problem is a set of independent segment reversals. Each block of 2k characters depends only on its own characters, so the same rule repeats block by block. Your job is to find where each block starts and where its reversal ends.
It is like a row of cards where you flip the first k of every 2k group by swapping ends and moving inward. The buffer is the card row, the two pointers are your hands, and the untouched cards are the tail that stays put.
Reversing a range in place is the two-pointer move. Put one pointer on the left end and one on the right end, swap them, and move both inward until they meet. The String Reversal subpattern applies that move to any range, not only the whole string.
The short tails need no separate branch. Set the right end to min(i + k - 1, n - 1). If fewer than k characters remain, the min picks the last index, so the whole tail reverses. The step of 2k skips the characters that must stay unchanged.
Worked example
Input: s = "abcdefghij", k = 4 Output: "dcbaefghji" Explanation: Blocks are 8 characters long. The first block is abcdefgh, and its first 4 characters reverse to dcba, so the block becomes dcbaefgh. The second block is ij. It has fewer than 4 characters, so all of it reverses to ji.
Approach 1: Brute force with block slices
A beginner splits the string into chunks and builds a new string. For each block, you slice out the first k characters and reverse that slice. Then you slice out the next k characters and keep them unchanged. You join the pieces at the end. The work is linear, because each character is sliced once. Each slice and reverse creates a new string, though. Those copies pile up in Java and Python.
Steps
- Create an empty list of output pieces.
- Set start to 0. While start is less than n, run the next two steps, then add 2k to start.
- Slice the first k characters of the block with s[start:start + k], and reverse that slice. Clamp the slice end to n.
- Slice the next k characters with s[start + k:start + 2k], and add them unchanged. An empty slice is fine when the string ends early.
- Join the pieces in order and return the result.
Dry run
Start with abcdefghij, k = 4. The blocks begin at 0 and 8.
Block at 0: the first 4 characters are abcd, and they reverse to dcba. The next 4 characters, efgh, go in unchanged. Pieces so far are dcba and efgh.
Block at 8: the slice ij is shorter than k, so it reverses to ji. The unchanged slice after it is empty. Joining the pieces gives dcbaefghji.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. The slices across all blocks cover each character once, and each character gets constant work, so the total is O(n). The pieces and the final join hold n characters, so the space is O(n). The extra allocations are a constant-factor cost that Big-O does not show.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseStr(self, s: str, k: int) -> str:
parts = []
# Walk over the blocks of 2k characters
for start in range(0, len(s), 2 * k):
# Reverse the first k characters of the block
parts.append(s[start:start + k][::-1])
# Keep the next k characters as they are
parts.append(s[start + k:start + 2 * k])
return ''.join(parts)The String Reversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
String Reversal
Part of Two Pointers
Approach 2: Two pointers on a mutable bufferOptimalString Reversal
The brute force pays for work it does not need. What's slow: every slice and reverse builds a new string, so characters get copied more than once. The insight that fixes it: a reversal is only swaps. Copy the input once into a mutable buffer, then swap inward inside each block. The tail beyond the first k characters of each block is never visited.
Why it is correct. Each swap exchanges two positions that mirror each other around the window center. When the loop ends, every position in the window holds the character that mirrored it, which is exactly a reversal. Blocks start at multiples of 2k and never overlap, so each character is handled once, and stepping by 2k leaves the next k characters unchanged as required.
Steps
- Copy s into a mutable character buffer. In C++, the string parameter is already a mutable copy, so use it directly.
- Set i to 0. While i is less than n, handle one block, then add 2k to i.
- Set left to i and right to min(i + k - 1, n - 1). The min clamps the window at the end of the string.
- While left is less than right, swap the characters at left and right, add 1 to left, and subtract 1 from right.
- After the loop, convert the buffer back to a string and return it.
Dry run
Start with abcdefghij, k = 4, n = 10. Each row is one step.
| Step | Action | left | right | Buffer after step |
|---|---|---|---|---|
| 1 | Start block i = 0 | 0 | 3 | abcdefghij |
| 2 | Swap positions 0 and 3 | 1 | 2 | dbcaefghij |
| 3 | Swap positions 1 and 2 | 2 | 1 | dcbaefghij |
| 4 | left is not less than right, block ends | 2 | 1 | dcbaefghij |
| 5 | Start block i = 8, clamp right to min(11, 9) | 8 | 9 | dcbaefghij |
| 6 | Swap positions 8 and 9 | 9 | 8 | dcbaefghji |
| 7 | Block ends, i = 16 is past n = 10 | 9 | 8 | dcbaefghji |
The buffer reads dcbaefghji, which is the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. Blocks are 2k long and the loop moves 2k at a time, so each character sits in at most one reversal window. A window of length L takes about L / 2 swaps, so all swaps together touch at most n characters. The loop runs about n / (2k) times, and the buffer holds n characters, which matches the output size.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseStr(self, s: str, k: int) -> str:
# Python strings are immutable, so work on a list
chars = list(s)
n = len(chars)
for i in range(0, n, 2 * k):
left = i
right = min(i + k - 1, n - 1)
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return ''.join(chars)Common mistakes
for i in range(0, n, k)steps by k instead of 2k. Every block gets reversed, including the blocks that must stay as they are. Step by2 * kso the loop lands on the start of each block.right = i + k - 1with no clamp. On a short last block the index passes n - 1, which raises an index error in Python and Java and reads garbage in C++. Usemin(i + k - 1, n - 1).while left != rightas the loop condition. With an even-length window the pointers step past each other and never match, so the loop never ends. Useleft < right.right = min(i + 2 * k - 1, n - 1), which reverses 2k characters instead of k. Onabcdefgwith k = 2 this givesdcbaefg, notbacdfeg.s[i] = ...assignment on a Python, Java, JavaScript, Go or C# string. Those strings cannot change, so the write fails or does nothing. Copy the text into a list, char array or byte slice first.- Returning
safter reversing a copy in Python or Java. The reversed text lives in the buffer, so join or convert the buffer and return that value.
Edge cases
k = 1withs = "abcd": each block reverses one character, so the output isabcd.klarger thannwiths = "abc", k = 10: one block covers the whole string, so the output iscba. The loop runs once and stops.- Exact fit with
s = "abcdefgh", k = 4: one full block of 2k characters, so the output isdcbaefgh. - Short last block with
s = "abcde", k = 2: the blocks areabcdande. The first becomesbacd, and the one-character tail stayse, so the output isbacde. - Single character with
s = "a", k = 1: left equals right from the start, no swap runs, and the output isa.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Reverse String II, with how to answer them.
Unlock the follow-upsReverse String II FAQ
What is the time complexity of Reverse String II?
The time complexity is O(n), where n is the length of s. Each character is swapped at most once, and the block loop adds only about n / (2k) iterations of constant work.
Why use two pointers for Reverse String II?
Reversing a range is the standard two-pointer swap. Each block needs exactly that move, and clamping the right pointer with min gives the short tail the same code path.
Can Reverse String II be solved in O(1) extra space?
Only when the input is a mutable array you are allowed to change, because then the swap loop uses O(1) extra space. In Python, Java, JavaScript, Go and C#, the string is immutable, so the mutable copy takes O(n) space. That copy is the same size as the output.
Does Python slicing clamp out-of-range indexes?
Slices do clamp, so s[start:start + k] stops at the end of the string without an error. Plain indexing does not clamp, so s[i] raises an IndexError when i is past the end. The optimal solution uses indexing, so it still needs the min clamp.
Does the slicing approach have a worse Big-O than the two-pointer approach?
No. Both approaches run in O(n) time and O(n) space. The slicing version creates many temporary strings, which costs more in practice in Java and Python.
Asked at
See which companies ask this — Pro
Related problems
- Reverse String · same technique: String Reversal
- Reverse Vowels of a String · same technique: String Reversal
- Reverse Integer · same technique: String Reversal
- Reverse Words in a String · same technique: String Reversal
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Remove Duplicates from Sorted Array · same pattern: Two Pointers
- Remove Element · same pattern: Two Pointers
- Merge Strings Alternately · same pattern: Two Pointers
- Move Zeroes · same pattern: Two Pointers